资讯专栏INFORMATION COLUMN

[Leetcode] Binary Tree Right Side View 二叉树右视图

hearaway / 2004人阅读

摘要:代码层序遍历复杂度时间空间对于二叉树思路我们同样可以借用层序遍历的思路,只要每次把这一层的最后一个元素取出来就行了,具体代码参见中的

Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example: Given the following binary tree,

   1            <---
 /   
2     3         <---
      
  5     4       <---

You should return [1, 3, 4].

深度优先搜索 复杂度

时间 O(b^(h+1)-1) 空间 O(h) 递归栈空间 对于二叉树b=2

思路

本题实际上是求二叉树每一层的最后一个节点,我们用DFS先遍历右子树并记录遍历的深度,如果这个右子节点的深度大于当前所记录的最大深度,说明它是下一层的最右节点(因为我们先遍历右边,所以每一层都是先从最右边进入),将其加入结果中。

代码
public class Solution {
    
    int maxdepth = 0;
    List res;
    
    public List rightSideView(TreeNode root) {
        res = new LinkedList();
        if(root!=null) helper(root,1);
        return res;
    }
    
    private void helper(TreeNode root, int depth){
        if(depth>maxdepth){
            maxdepth = depth;
            res.add(root.val);
        }
        if(root.right!=null) helper(root.right, depth+1);
        if(root.left!=null) helper(root.left, depth+1);
    }
    
}
层序遍历 Level Order Traversal 复杂度

时间 O(b^(h+1)-1) 空间 O(b^h) 对于二叉树b=2

思路

我们同样可以借用层序遍历的思路,只要每次把这一层的最后一个元素取出来就行了,具体代码参见Binary Tree Traversal中的Binary Tree Level Order Traversal

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

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

相关文章

  • LeetCode 精选TOP面试题【51 ~ 100】

    摘要:有效三角形的个数双指针最暴力的方法应该是三重循环枚举三个数字。总结本题和三数之和很像,都是三个数加和为某一个值。所以我们可以使用归并排序来解决这个问题。注意因为归并排序需要递归,所以空间复杂度为 ...

    Clect 评论0 收藏0
  • [Leetcode] Binary Tree Paths 叉树路径

    摘要:递归法复杂度时间空间递归栈空间对于二叉树思路简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。当遇到最小公共祖先的时候便合并路径。需要注意的是,我们要单独处理目标节点自身是最小公共祖先的情况。 Root To Leaf Binary Tree Paths Given a binary tree, return all root-to-leaf pat...

    Vicky 评论0 收藏0
  • [Leetcode] Invert Binary Tree 翻转叉树

    摘要:原题链接递归法复杂度时间空间递归栈空间思路这个难倒大神的题也是非常经典的一道测试对二叉树遍历理解的题。递归的终止条件是当遇到空节点或叶子节点时,不再交换,直接返回该节点。代码给出的是后序遍历的自下而上的交换,先序遍历的话就是自上而下的交换。 Invert Binary Tree Invert a binary tree. 4 / 2 7 / ...

    leone 评论0 收藏0
  • LeetCode 104 Maximum Depth of Binary Tree 叉树最大深度

    LeetCode 104 Maximum Depth of Binary Tree难度:Easy 题目描述:找到一颗二叉树的最深深度。Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down ...

    PiscesYE 评论0 收藏0

发表评论

0条评论

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