二叉树的后序遍历

145 二叉树的后序遍历

后序遍历,先访问左子树然后访问右子树然后访问根节点。

 C++代码

/**
 * 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> v;
        stack<TreeNode*> s;
        TreeNode* cur = root;
        TreeNode* pre = NULL;
//迭代写法,利用pre记录上一个访问过的结点,与当前结点比较,如果是当前结点的子节点,说明其左右结点均已访问,将当前结点出栈,更新pre记录的对象。 s.push(cur);
while(!s.empty()&&cur!=NULL){ cur = s.top(); if((cur->right==NULL && cur->left==NULL)|| (pre!=NULL&&(pre==cur->left||pre==cur->right))){ v.push_back(cur->val); s.pop(); pre = cur; }else{ if(cur->right!=NULL){ s.push(cur->right); } if(cur->left!=NULL){ s.push(cur->left); } } } return v; } };

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        TreeNode cur = root;
        TreeNode pre = null;
        while(!s.isEmpty()&&cur!=null){
            cur = s.peek();
            if((cur.left==null&&cur.right==null)||
               ((pre!=null)&&(pre==cur.left||pre==cur.right))){
                list.add(cur.val);
                s.pop();
                pre = cur;
            }else{
                if(cur.right!=null){
                    s.push(cur.right);
                }
                if(cur.left!=null){
                    s.push(cur.left);
                }
            }
        }
        return list;
    }
}
原文地址:https://www.cnblogs.com/dong973711/p/10828158.html