LeetCode 145 Binary Tree Postorder Traversal(二叉树的兴许遍历)+(二叉树迭代)
Posted wzjhoutai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 145 Binary Tree Postorder Traversal(二叉树的兴许遍历)+(二叉树迭代)相关的知识,希望对你有一定的参考价值。
翻译
给定一个二叉树。返回其兴许遍历的节点的值。
比如:
给定二叉树为 {1。 #, 2, 3}
1
2
/
3
返回 [3, 2, 1]
备注:用递归是微不足道的,你能够用迭代来完毕它吗?
原文
Given a binary tree, return the postorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
分析
直接上代码……
vector<int> postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
v.push_back(root->val);
}
return v;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> v;
void postorderTraversalIter(TreeNode *root, stack<TreeNode*> &stac) {
if (root == NULL) return;
bool hasLeft = root->left != NULL;
bool hasRight = root->right != NULL;
stac.push(root);
if (hasRight)
stac.push(root->right);
if (hasLeft)
stac.push(root->left);
if (!hasLeft && !hasRight)
v.push_back(root->val);
if (hasLeft) {
root = stac.top();
stac.pop();
postorderTraversalIter(root, stac);
}
if (hasRight) {
root = stac.top();
stac.pop();
postorderTraversalIter(root, stac);
}
if (hasLeft || hasRight)
v.push_back(stac.top()->val);
stac.pop();
}
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> stac;
postorderTraversalIter(root, stac);
return v;
}
};
另有两道相似的题目:
LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
LeetCode 144 Binary Tree Preorder Traversal(二叉树的前序遍历)+(二叉树、迭代)
以上是关于LeetCode 145 Binary Tree Postorder Traversal(二叉树的兴许遍历)+(二叉树迭代)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 145. Binary Tree Postorder Traversal
LeetCode 145:Binary Tree Postorder Traversal
leetcode145. Binary Tree Postorder Traversal
LeetCode 145: Binary Tree Postorder Traversal