zoukankan      html  css  js  c++  java
  • 二叉树后序遍历

    二叉树后序遍历,分为递归方法和非递归方法:

    递归:

    private static List<Integer> postList = new ArrayList<>();
    public static List<Integer> postorderTraversalRec(TreeNode root){
        if (null == root){
            return postList;
        }
        postorder(root);
        return postList;
    }
    private static void postorder(TreeNode root){
        if (null == root){
            return;
        }
        postorder(root.left);
        postorder(root.right);
        postList.add(root.val);
    }

    非递归:

    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (null == root){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);
            if (null != node.left){
                stack.push(node.left);
            }
            if (null != node.right){
                stack.push(node.right);
            }
        }
        Collections.reverse(list);
        return list;
    }
  • 相关阅读:
    prayer OJ M
    51nod1295
    纪念第一次ak。。。
    noip2007-4
    51nod1344
    51nod1079
    51nod1537
    51nod1269Devu and Flowers
    python基本数据类型之列表list
    Python基本数据类型
  • 原文地址:https://www.cnblogs.com/earthhouge/p/11262935.html
Copyright © 2011-2022 走看看