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