标签:
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]
.
分析:
这题有迷惑性,不要以为只是让你找出最右边的节点,如果左边节点比右边节点高,那么左边节点的右边部分也要输出来。
这题可以按层获取树的节点,然后把每层最右边的找出来。
Code from: http://www.programcreek.com/2014/04/leetcode-binary-tree-right-side-view-java/
/** * 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) { ArrayList<Integer> result = new ArrayList<Integer>(); if (root == null) return result; LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while (queue.size() > 0) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode top = queue.poll(); // the first element in the queue (right-most of the tree) if (i == 0) { result.add(top.val); } // add right first if (top.right != null) { queue.add(top.right); } // add left if (top.left != null) { queue.add(top.left); } } } return result; } }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5731367.html