LeetCode 145 Binary Tree Postorder Traversal(二叉樹的興許遍歷)+(二叉樹、叠代)
阿新 • • 發佈:2017-08-04
int truct fin for data- right class span popu
翻譯
給定一個二叉樹。返回其興許遍歷的節點的值。
比如:
給定二叉樹為 {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(二叉樹的興許遍歷)+(二叉樹、叠代)