资讯专栏INFORMATION COLUMN

94. Binary Tree Inorder Traversal

dackel / 2303人阅读

摘要:题目解答合并两个直接就好啦的方法很巧妙,当时想了很久也没做出来,所以这里标注一下

题目:
Given a binary tree, return the inorder traversal of its nodes" values.

For example:
Given binary tree [1,null,2,3],

   1
    
     2
    /
   3

return [1,3,2].

Note: Recursive solution is trivial, could you do it iteratively?

解答:

Recursive:

public List inorderTraversal(TreeNode root) {
    List result = new ArrayList();
    if (root == null) return result;
    if (root.left == null && root.right == null) {
        result.add(root.val);
        return result;
    }
    
    //合并两个list,直接addAll就好啦
    result.addAll(inorderTraversal(root.left));
    result.add(root.val);
    result.addAll(inorderTraversal(root.right));
    
    return result;
}

Iteratively

//Iterative的方法很巧妙,当时想了很久也没做出来,所以这里标注一下
    public List inorderTraversal(TreeNode root) {
        List list = new ArrayList();
        Stack stack = new Stack();
        
        TreeNode curt = root;
        while (curt != null || !stack.isEmpty()) {
            while (curt != null) {
                stack.push(curt);
                curt = curt.left;
            }
            curt = stack.pop();
            list.add(curt.val);
            curt = curt.right;
        }
        return list;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64872.html

相关文章

  • leetcode讲解--94. Binary Tree Inorder Traversal

    摘要:题目地址嗯,经典的题目,中序遍历二叉树。代码如下中序遍历先序遍历后序遍历是不是简单的不要不要的,递归就是这么美。右孩子后压栈全部释放出来嗯,总的来说用迭代遍历确实烧脑,没什么性能上的特殊需求还是用递归写法吧,对程序员友好哦。 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder travers...

    henry14 评论0 收藏0
  • leetcode 94. Binary Tree Inorder Traversal

    摘要:题目要求中序遍历树,并将遍历结果添加到数组中。分别用递归和循环的方式结局。如果当前节点存在左子节点,则继续遍历左子树直到最后一个左子节点。如果栈顶元素有右子节点,则将其右子节点压入栈中作为,再继续遍历的左子节点。当和都为空时,遍历结束。 题目要求 Given a binary tree, return the inorder traversal of its nodes values....

    wpw 评论0 收藏0
  • LeetCode 之 JavaScript 解答第94题 —— 二叉树的中序遍历

    摘要:小鹿题目二叉树中序遍历给定一个二叉树,返回它的中序遍历。通常递归的方法解决二叉树的遍历最方便不过,但是我还是喜欢增加点难度,用一般的迭代循环来实现。 Time:2019/4/25Title:Binary Tree Inorder TraversalDifficulty: MediumAuthor:小鹿 题目:Binary Tree Inorder Traversal(二叉树中序遍历...

    Jason 评论0 收藏0
  • 二叉树遍历算法收集(先序 preorder,后序 postorder,中序 inorder) 循环+

    摘要:指的是的位置。算法比较简单,算法比较难想,可是原题都说了 preorder: root-left-rightinorder: left-root-rightpostorder: left-right-root order指的是root的位置。 recursive算法比较简单,iterative算法比较难想,可是leetcode原题都说了: recursive method is tri...

    沈建明 评论0 收藏0
  • [Leetcode] Construct Binary Tree from Traversal 根据

    摘要:二分法复杂度时间空间思路我们先考察先序遍历序列和中序遍历序列的特点。对于中序遍历序列,根在中间部分,从根的地方分割,前半部分是根的左子树,后半部分是根的右子树。 Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a tree, constru...

    caoym 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<