199. Binary Tree Right Side View

网友投稿 698 2022-09-04

199. Binary Tree Right Side View

199. 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先遍历右子树并记录遍历的深度,如果这个右子节点的深度大于当前所记录的最大深度,说明它是下一层的最右节点(因为我们先遍历右边,所以每一层都是先从最右边进入),将其加入结果中。

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */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); }}

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public List rightSideView(TreeNode root) { if(root == null) return Collections.emptyList(); List result = new ArrayList(); Queue queue = new LinkedList(); queue.add(root); //int level = 0; while(!queue.isEmpty()){ int size = queue.size(); for(int i=0;i

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:187. Repeated DNA Sequences
下一篇:Composer依赖管理 – PHP的利器(composer环境变量)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~