首页 > 其他 > 详细

二叉树中序遍历

时间:2020-03-21 03:56:24      阅读:46      评论:0      收藏:0      [点我收藏+]

94. 二叉树的中序遍历

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
   1
         2
    /
   3

输出: [1,3,2]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

public class T94 {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        TreeNode tempRoot = root;
        while (tempRoot != null || !stack.isEmpty()) {
            while (tempRoot != null) {
                stack.push(tempRoot);
                tempRoot = tempRoot.left;
            }
            //root左为空
            TreeNode node = stack.pop();
            list.add(node.val);
            tempRoot = node.right;
        }
        return list;
    }
}

 

二叉树中序遍历

原文:https://www.cnblogs.com/zzytxl/p/12535723.html

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