题:
给定一个二叉树,返回它的后序遍历。
例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,2,3]
码:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(root){
stack<TreeNode*> sk;
TreeNode *cut=NULL;
TreeNode *cur=root;//从下到上的拦截点,防止回退
while(cur||sk.size()){
if(cur){
sk.push(cur);
cur=cur->left;
}else{
cur=sk.top();
if(cur->right&&cur->right!=cut)//看右子节点
cur=cur->right;
else{
res.push_back(cur->val);
sk.pop();
cut=cur;
cur=NULL;
}
}
}
}
return res;
}
源:
https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/