给定一个二叉树,返回其后续遍历的节点的值。
例如:
给定二叉树为 {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(二叉树的前序遍历)+(二叉树、迭代)