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:层次遍历。每次保留每层的最后一个节点就可以了。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
		if(root==null) return res;
		List<TreeNode> queue = new ArrayList<TreeNode>();
		int low = 0;
		int high = 1;
		int ceng = 0;
		queue.add(root);
		while(low<high){
			TreeNode cur = queue.get(low);			
			if(cur.left!=null){
				queue.add(cur.left);
				high++;
			}
			if(cur.right!=null){
				queue.add(cur.right);
				high++;
			}
			if(ceng==low){
				res.add(cur.val);
				ceng = high-1;
			}
			low++;
		}
		return res;
    }
}
解法2:层次遍历。和解法1思路一样,只是代码更加精简。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();//队列,用于层次遍历
        List<Integer> res = new ArrayList<Integer>();//结果
        if(root==null) return res;
        int level = 1;
        queue.add(root);
        while(queue.size()>0){
            TreeNode node = queue.poll();
            if(node.left != null)
                queue.add(node.left);
            if(node.right != null)
                queue.add(node.right);
            if(--level == 0){
                level = queue.size();
                res.add(node.val);
            }
        }
        return res;
    }
} 
                   
                   
                   
                   
                            
 
                             本文深入探讨了如何通过层次遍历的方法解决二叉树右视图问题,并提供了两种实现解决方案。第一种方法采用队列进行层次遍历,保留每层的最后一个节点;第二种方法同样使用层次遍历,但代码更为简洁。通过实例演示,清晰展示了二叉树右视图的求解过程。
本文深入探讨了如何通过层次遍历的方法解决二叉树右视图问题,并提供了两种实现解决方案。第一种方法采用队列进行层次遍历,保留每层的最后一个节点;第二种方法同样使用层次遍历,但代码更为简洁。通过实例演示,清晰展示了二叉树右视图的求解过程。
           
       
           
                 
                 
                 
                 
                 
                
               
                 
                 
                 
                 
                
               
                 
                 扫一扫
扫一扫
                     
              
             
                  
 被折叠的  条评论
		 为什么被折叠?
被折叠的  条评论
		 为什么被折叠?
		 
		  到【灌水乐园】发言
到【灌水乐园】发言                                
		 
		 
    
   
    
   
             
            


 
            