Binary Tree Postorder Traversal
2014-04-09 16:49
162 查看
/* * Solution.cpp * * Created on: 2014年4月9日 * Author: William */ #include <iostream> #include <vector> #include <stack> using namespace std; // Definition for binary tree struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; class Solution { public: void postorderTraversalRecursive(TreeNode *root, vector<int> *ans) { if (root != NULL) { postorderTraversalRecursive(root->left, ans); postorderTraversalRecursive(root->right, ans); ans->push_back(root->val); } } vector<int> postorderTraversal(TreeNode *root) { // Recursive /*vector<int> ans; postorderTraversalRecursive(root, &ans); return ans;*/ // Iterative vector<int> ans; if (root == NULL) return ans; stack<TreeNode*> stk; stk.push(root); TreeNode *cur; while (!stk.empty()) { cur = stk.top(); if (cur->left == NULL && cur->right == NULL) { stk.pop(); ans.push_back(cur->val); } else { // This part is very clever: // If the current node has left/right child, we push the children nodes into the stack // in right-left order(which makes the pop order becomes left-right). // Then we make the current node has no child, so it can be treated as a leaf. // Basically, this way we put all the nodes into the stack in post-order(reverse). // This way, we avoid using flag to indicate visited node. if (cur->right != NULL) { stk.push(cur->right); cur->right = NULL; } if (cur->left != NULL) { stk.push(cur->left); cur->left = NULL; } } } return ans; } }; //int main() { // return 0; //}
相关文章推荐
- Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- [leetcode][tree] Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- LeeCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode::Construct Binary Tree from Inorder and Postorder Traversal
- 5. Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal
- leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
- Data Structure: How to traversal Binary Tree Iteratively (Preorder, Inorder and Postorder)
- LeetCode OJ 106. Construct Binary Tree from Inorder and Postorder Traversal
- Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal dfs,深度搜索
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode--Binary Tree Postorder Traversal
- leetcode--ConstructBinaryTreefromInorderandPostorderTraversal
- LeetCode -- Binary Tree Postorder Traversal
- Lettcode_145_Binary Tree Postorder Traversal
- 根据中序和后序序列重建二叉树 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode 7 Binary Tree Postorder Traversal