Binary Tree Postorder Traversal --leetcode
2017-04-26 21:41
369 查看
原题链接:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/
题目大意:后序遍历二叉树
解题思路:后序遍历二叉树的步骤:后序遍历二叉树的左子树,后序遍历二叉树的右子树,訪问根结点。
非递归实现时,用一个栈模拟遍历过程。由于訪问完左子树后訪问右子树。栈中元素要起到转向訪问其右子树的作用,可是不能像先序和中序遍历那样出栈就可以,由于根结点时最后訪问的。那么什么时候出栈呢?我们须要一个指针pre来记录前一次訪问的结点。假设pre是根结点的右子树,则说明根结点的右子树訪问完了,此时根结点就能够出栈了。
class Solution{ public: vector<int> postorderTraversal(TreeNode *root) { vector<int> res; stack<TreeNode*> s; TreeNode* pre=NULL; while(root||!s.empty()) { if(root) { s.push(root); root=root->left; } else if(s.top()->right!=pre) { root=s.top()->right; pre=NULL; } else { res.push_back(s.top()->val); pre=s.top(); s.pop(); } } return res; } };
时间复杂度:O(N),每一个结点訪问仅一次。
空间复杂度:O(lgN)。即栈的大小树深。
后序遍历是三种遍历中最难得一种,与先序遍历和中序遍历的差别就是:须要一个指针来辅助推断能否够訪问根结点。
相关文章推荐
- Construct Binary Tree from Inorder and Postorder Traversal || LeetCode
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode106:Construct Binary Tree from Inorder and Postorder Traversal
- 开始刷leetcode day72:Binary Tree Postorder Traversal
- LeetCode题解-145-Binary Tree Postorder Traversal
- [Leetcode] Binary Tree Postorder Traversal
- Leetcode 之Binary Tree Postorder Traversal(47)
- [JAVA]LeetCode106 Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - Binary Tree Postorder Traversal
- leetcode: Binary Tree Postorder Traversal
- 【Leetcode】【python】Binary Tree Postorder Traversal
- 73_leetcode_Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]: 145: Binary Tree Postorder Traversal
- <LeetCode OJ> 106. Construct Binary Tree from Inorder and Postorder Traversal
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- [LeetCode]145 Binary Tree Postorder Traversal
- [leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal@Java结题报告
- Binary Tree Postorder Traversal leetcode145
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal