二叉树的后续遍历
2018-02-07 本文已影响17人
球球球球笨
整理一份代码,之后要熟练掌握
/**
* Definition for binary tree
* 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> v;
postOrder(root, v);
return v;
}
void postOrder(TreeNode *root, vector<int>& v) {
if( root != NULL ) {
postOrder(root->left, v);
postOrder(root->right, v);
v.push_back(root->val);
}
}
};
//后序遍历非递归写法
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
vector<int> v;
if(root == NULL) return v;
stack<TreeNode*> s;
s.push(root);
TreeNode* temp = NULL;
while(!s.empty()) {
temp = s.top();
if(temp->left == NULL && temp->right == NULL) {
v.push_back(temp->val);
s.pop();
}else {
if(temp->right) {
s.push(temp->right);
temp -> right = NULL;
}
if(temp->left) {
s.push(temp->left);
temp -> left = NULL;
}
}
}
return v;
}
};
//特别要注意入栈顺序