【LeetCode】199. Binary Tree Right Side View-二叉树右视图结点
2017-03-28 10:37
447 查看
一、描述:
水平面上,从右向左能看到的结点构成的图形,依次输出。原题样例二叉树中,右视图能看到的结点从上而下排成一列,依次是1-3-4;
以二叉树最大深度作为循环条件,使用Queue队列存储每一层的结点,并输出每一层最后一结点;
类似于LeetCode 513
二、思路:
输出二叉树右视图所有结点,即输出每一层的最后一结点;水平面上,从右向左能看到的结点构成的图形,依次输出。原题样例二叉树中,右视图能看到的结点从上而下排成一列,依次是1-3-4;
以二叉树最大深度作为循环条件,使用Queue队列存储每一层的结点,并输出每一层最后一结点;
类似于LeetCode 513
三、代码:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<Integer> rightSideView(TreeNode root) { 12 List<Integer> list = new ArrayList<Integer>(); 13 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 14 int depth = depth(root); 15 queue.offer(root); 16 while((depth--)>=1){ 17 TreeNode node; 18 int size = queue.size(); 19 for(int i=0;i<size;i++){ 20 if(i==size-1){ //判断是否为该层的最后一结点 21 node = queue.peek(); 22 list.add(node.val); 23 } 24 node = queue.remove(); 25 if(node.left!=null){ 26 queue.offer(node.left); 27 } 28 if(node.right!=null){ 29 queue.offer(node.right); 30 } 31 } 32 } 33 return list; 34 } 35 36 public int depth(TreeNode root){ //求二叉树最大深度 37 if(root==null){ 38 return 0; 39 } 40 if(root.left==null && root.right==null){ 41 return 1; 42 } 43 int left = depth(root.left); 44 int right = depth(root.right); 45 return left<right ? right+1 : left+1; 46 } 47 }
相关文章推荐
- 【Leetcode】查找二叉树中任意结点的最近公共祖先(LCA问题)
- LeetCode 199. Binary Tree Right Side View(二叉树右侧视图)
- 【Leetcode】查找二叉树中任意结点的最近公共祖先(LCA问题)
- LeetCode-199. Binary Tree Right Side View (JAVA)(二叉树最右侧结点)
- [LeetCode] 199. Binary Tree Right Side View 二叉树的右侧视图
- LeetCode 96. Unique Binary Search Trees Python Solution, Catalan数 结点数为n的不同形态的二叉树一共有多少种
- Leetcode 199. 二叉树的右视图
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- 【Leetcode】Binary Tree Paths 二叉树根结点到所有叶子结点的路径
- [LeetCode] Binary Tree Right Side View 二叉树的右侧视图
- Leetcode 116 Populating Next Right Pointers in Each Node 二叉树填充next指针指向右侧结点
- Leetcode 117 Populating Next Right Pointers in Each Node II 二叉树填充next指针指向右侧结点 II
- Leetcode 199 Binary Tree Right Side View 二叉树右视图
- LeetCode199. 二叉树的右视图
- 打印二叉树第K层的所有结点
- Binary Tree Maximum Path Sum (二叉树路径和的最大值) 【leetcode】
- [Leetcode] Binary tree maximum path sum求二叉树最大路径和
- LeetCode:求二叉树的深度
- leetcode 111-二叉树最小深度
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)