[LEETCODE] Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
思路:
Postorder: 左右中。
注意点:
1. Recursive method iterate 条件先判断root 是否存在.
2. 对于Non-recursive method. 用两个vector,vector1存树上的node,vector2存值;
1) 开始的判断root是否为NULL 不要忘了,且在vector1中存入root;
2) 循环结束条件为vector1为空; 循环内容是,存node值到vector2,存node的左右(先左后右)node到vector1
3) vector2存的顺序是反的,所以最后用一个reverse()函数
1) 开始的判断root是否为NULL 不要忘了,且在vector1中存入root;
2) 循环结束条件为vector1为空; 循环内容是,存node值到vector2,存node的左右(先左后右)node到vector1
3) vector2存的顺序是反的,所以最后用一个reverse()函数
代码1(Recursive):
/**代码2(Non-recursive):
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//iteration method
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
postorder(root, result);
return result;
}
void postorder(TreeNode *root, vector<int> &result){
if(!root) return;
postorder(root->left , result);
postorder(root->right, result);
result.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
if(root == NULL) return result;
vector<TreeNode *> stack;
stack.push_back(root);
TreeNode *node = root;
while(stack.size() !=0){
node = stack.back();
result.push_back(node->val);
stack.pop_back();
if(node->left != NULL){
stack.push_back(node->left );
}
if(node->right!= NULL){
stack.push_back(node->right);
}
}
reverse(result.begin(), result.end());
return result;
}
No comments:
Post a Comment