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?
Subscribe to see which companies asked this question
/**
* 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> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root==NULL) return res;
stack<TreeNode*> sta;
sta.push(root);
while(!sta.empty()) {
TreeNode *top = sta.top();
if(top->left!=NULL) {
sta.push(top->left);
top->left = NULL;
} else if(top->right!=NULL) {
sta.push(top->right);
top->right = NULL;
} else {
sta.pop();
res.push_back(top->val);
}
}
return res;
}
};
本文介绍了一种不使用递归的方法来完成二叉树节点值的后序遍历。通过栈结构实现迭代过程,巧妙地避免了左子树和右子树的重复访问,提供了一个简洁高效的解决方案。
302

被折叠的 条评论
为什么被折叠?



