Leetcode: Binary Tree Postorder Traversal
思路:
1. 堆栈模拟
总结:
1. 使用堆栈的话, 后续遍历和前序遍历并不是对称的, 和递归函数的写法大不相同
代码:
自己最初写的代码, 遍历一遍后, 树已经被破坏掉了
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if(root == NULL) return res; stack<TreeNode*> stc; stc.push(root); while(!stc.empty()) { TreeNode* node = stc.top(); if(node->left == NULL && node->right == NULL) { res.push_back(node->val); stc.pop(); } if(node->right != NULL) { stc.push(node->right); node->right = NULL; } if(node->left != NULL) { stc.push(node->left); node->left = NULL; } } return res; } };
参考别人的代码, 做的改进
class Solution { public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; if(root == NULL) return res; vector<TreeNode*> stc; stc.push_back(root); while(!stc.empty()) { TreeNode* node = stc.back(); res.push_back(node->val); stc.pop_back(); if(node->left != NULL) { stc.push_back(node->left); } if(node->right != NULL) { stc.push_back(node->right); } } reverse(res.begin(), res.end()); return res; } };