首页 > 其他 > 详细

二叉树后序遍历

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

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

递归:

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;
}

二叉树后序遍历

原文:https://www.cnblogs.com/earthhouge/p/11262935.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!