当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

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

作者:小梦 来源: 网络 时间: 2024-01-16 阅读:

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<Integer> res;        public List<Integer> rightSideView(TreeNode root) {        res = new LinkedList<Integer>();        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

网友最爱