码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode 199] Binary Tree Right Side View

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

标签:java   算法   leetcode   bfs   dfs   

题目链接: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

标签:java   算法   leetcode   bfs   dfs   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!