首页 > 其他 > 详细

[LeetCode 199] Binary Tree Right Side View

时间:2015-04-15 19:39:05      阅读:186      评论:0      收藏:0      [点我收藏+]

题目链接:binary-tree-right-side-view


import java.util.ArrayList;
import java.util.List;


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

public class BinaryTreeRightSideView {

	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}
	
	//解法一, 层次遍历法
//	210 / 210 test cases passed.
//	Status: Accepted
//	Runtime: 300 ms
//	Submitted: 0 minutes ago
	
	//时间复杂度O(n),空间复杂度O(n)
	public List<Integer> rightSideView(TreeNode root) {
		return bfs(root);
	}
    public List<Integer> bfs(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        List<TreeNode> levelOrder = new ArrayList<TreeNode>();
        if(root == null)	return result;
        
        levelOrder.add(root);
        while(!levelOrder.isEmpty()) {
        	int len = levelOrder.size();
        	result.add(levelOrder.get(len - 1).val);
        	for(int i = 0; i < len; i ++) {
        		TreeNode node = levelOrder.remove(0);
        		if(node.left != null)	levelOrder.add(node.left);
        		if(node.right != null)	levelOrder.add(node.right);
        	}
        }
        return result;
    }
    
    //解法二:深度遍历法
//    210 / 210 test cases passed.
//    Status: Accepted
//    Runtime: 229 ms
//    Submitted: 0 minutes ago

    //时间复杂度O(n),空间复杂度O(n)
	public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        dfs(root, result, 0);
		return result;
	}
    public void dfs(TreeNode root, List<Integer> result, int level) {
    	if(root == null) return;
    	if(level == result.size())
    		result.add(root.val);
    	dfs(root.right, result, level + 1);
    	dfs(root.left, result, level + 1);
    }
    
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


[LeetCode 199] Binary Tree Right Side View

原文:http://blog.csdn.net/ever223/article/details/45062305

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!