leetcode--Binary Tree Right Side View

来源:互联网 发布:excel2010数据透视图 编辑:程序博客网 时间:2024/06/06 03:54

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].


题意:给定一颗二叉树,假设你站在二叉树的右边。从你的方向看出去,求你能见到的所有节点的值。

分类:二叉树


解法1:层次遍历。每次保留每层的最后一个节点就可以了。

[java] view plain copy
  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> res = new ArrayList<Integer>();  
  13.         if(root==nullreturn res;  
  14.         List<TreeNode> queue = new ArrayList<TreeNode>();  
  15.         int low = 0;  
  16.         int high = 1;  
  17.         int ceng = 0;  
  18.         queue.add(root);  
  19.         while(low<high){  
  20.             TreeNode cur = queue.get(low);            
  21.             if(cur.left!=null){  
  22.                 queue.add(cur.left);  
  23.                 high++;  
  24.             }  
  25.             if(cur.right!=null){  
  26.                 queue.add(cur.right);  
  27.                 high++;  
  28.             }  
  29.             if(ceng==low){  
  30.                 res.add(cur.val);  
  31.                 ceng = high-1;  
  32.             }  
  33.             low++;  
  34.         }  
  35.         return res;  
  36.     }  
  37. }  


解法2:层次遍历。和解法1思路一样,只是代码更加精简。

[java] view plain copy
  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.         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();//队列,用于层次遍历  
  13.         List<Integer> res = new ArrayList<Integer>();//结果  
  14.         if(root==nullreturn res;  
  15.         int level = 1;  
  16.         queue.add(root);  
  17.         while(queue.size()>0){  
  18.             TreeNode node = queue.poll();  
  19.             if(node.left != null)  
  20.                 queue.add(node.left);  
  21.             if(node.right != null)  
  22.                 queue.add(node.right);  
  23.             if(--level == 0){  
  24.                 level = queue.size();  
  25.                 res.add(node.val);  
  26.             }  
  27.         }  
  28.         return res;  
  29.     }  
  30. }  

原文链接http://blog.csdn.net/crazy__chen/article/details/46574283