码迷,mamicode.com
首页 > 其他好文 > 详细

145. 二叉树的后序遍历

时间:2019-07-13 13:35:19      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:integer   tree   ble   int   roo   节点   sum   end   linked   

技术图片

递归

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {   
        List<Integer> ls = new ArrayList<Integer>();
        end(root, ls);
        return ls;
    }

    public static void end(TreeNode T, List<Integer> ls) {
        if (T == null)
            return;
        end(T.left, ls);
        end(T.right, ls);
        ls.add(T.val);
    }
}

递推有点难

public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<TreeNode> ls = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();
        if (root == null) {
            return output;
        }
        ls.add(root);
        while (!ls.isEmpty()) {
            TreeNode node = ls.pollLast();
            output.addFirst(node.val);
            if (node.left != null) {
                ls.add(node.left);
            }
            if (node.right != null) {
                ls.add(node.right);
            }
        }
        return output;
    }
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/er-cha-shu-de-hou-xu-bian-li-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public List<Integer> postorderTraversal(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    if(root == null) return res;
    Stack<TreeNode> stack = new Stack<>();
    TreeNode cur = root;
    TreeNode last = null;
    
    while(cur != null || !stack.isEmpty()){
        while(cur != null){
            stack.push(cur);
            cur = cur.left;
        }
        cur = stack.peek();
        if(cur.right == null || cur.right == last){
            res.add(cur.val);
            stack.pop();
            last = cur;
            cur = null;
        }else{
            cur = cur.right;
        }
    }
    return res;
}

}

public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stk1 = new Stack<>();
        Stack<Character> stk2 = new Stack<>();
        while(root!=null || !stk1.isEmpty()){
            while(root!=null){
                stk1.push(root);
                stk2.push('n');//n=>no=>访问的非当前节点
                root = root.left;
            }
            while(!stk1.isEmpty() && stk2.peek()=='y')//y=>yes=>访问的当前节点
            {
                list.add(stk1.pop().val);
                stk2.pop();
            }
            if(!stk1.isEmpty()){
                stk2.pop();
                stk2.push('y');
                root = stk1.peek();
                root = root.right;
            }
        }
        return list;
    }

145. 二叉树的后序遍历

标签:integer   tree   ble   int   roo   节点   sum   end   linked   

原文地址:https://www.cnblogs.com/cznczai/p/11180083.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!