首页 > 其他 > 详细

94. 二叉树的中序遍历

时间:2021-09-01 15:02:08      阅读:17      评论:0      收藏:0      [点我收藏+]

二叉树的中序遍历。

中序遍历我记为 左 - 中- 右

技术分享图片

Inorder (Left, Root, Right) : 4 2 5 1 3

树的遍历大部分都是可以给出迭代和递归两种做法的,两种做法的时间和空间复杂度一样,时间都是O(n),空间都是O(h)。

递归实现:

class Solution {
    public List<Integer> inorderTraversal(TreeNode head) {
        List<Integer> list=new ArrayList<>();
        if(head==null){
            return list;
        }
        process(head,list);
        return list;
    }

    public void process(TreeNode node,List<Integer> list){
        if(node==null){
            return;
        }
        process(node.left,list);
        list.add(node.val);
        process(node.right,list);
    }
}

  

非递归实现:

中:左中右
第一阶段:先遍历左子树入stack
第二阶段:弹出并打印cur,cur.right重复阶段一
class Solution {
    public List<Integer> inorderTraversal(TreeNode head) {
        if(head==null){
            return new ArrayList<>();
        }
        List<Integer> result=new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur=head;
        while (!stack.isEmpty()||cur!=null){
            if(cur!=null){
                stack.push(cur);
                cur=cur.left;
            }else {
                cur=stack.pop();
                result.add(cur.val);
                cur=cur.right;
            }
        }
        return result;
    }
}

  

94. 二叉树的中序遍历

原文:https://www.cnblogs.com/iwyc/p/15211175.html

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