标签:tree node null logs result ret 版本 return 使用 指针
思路一:递归版本
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == nullptr) return result; postorder(root, result); return result; } void postorder(TreeNode *cur, vector<int> &result) { if(cur->left != nullptr) postorder(cur->left, result); if(cur->right != nullptr) postorder(cur->right, result); result.push_back(cur->val); } };
思路二:非递归版本,前序遍历中使用了一个额外的指针,这里使用times记录节点出栈的次数,更加方便直观
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: struct Node{ TreeNode *node; int times; Node(TreeNode *tmp=nullptr):node(tmp), times(0){} }; public: vector<int> postorderTraversal(TreeNode* root) { vector<int> result; if(root == nullptr) return result; stack<Node> s; Node current(root); s.push(current); while(!s.empty()) { current = s.top(); if(current.times == 0) { ++s.top().times; if(current.node->left != nullptr) s.push(Node(current.node->left)); } else if(current.times == 1) { ++s.top().times; if(current.node->right != nullptr) s.push(Node(current.node->right)); } else { result.push_back(current.node->val); cout<<"hi"<<endl; s.pop(); } } return result; } };
Binary Tree Postorder Traversal
标签:tree node null logs result ret 版本 return 使用 指针
原文地址:http://www.cnblogs.com/chengyuz/p/6657524.html