leetcode oj java 199. Binary Tree Right Side View

来源:互联网 发布:湖人王朝时期科比数据 编辑:程序博客网 时间:2024/06/06 02:03

一、问题描述:

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

Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

二、解决思路:

层次遍历二叉树,遇到最右边的结点加入到list中即可。现在关键是如何判断什么时候遇到了‘最右边的结点’。

我们知道,在层次遍历的时候一般会用队列Queue来辅助,我们首先在队列中放入root结点,再放入root的左右孩子,每次pop出一个节点的时候都会

add这个节点的左右节点。

那么我们稍微修改一下,放入在队列中压入root之后,再压入一个null.

pop出队列中的元素tmp,判断tmp是否是空,如果为空而且队列也为空直接返回,否则说明已经遍历完一层了,此时在队列中再压入Null。

否则 判断下一个是否为null, 是的话把pop出的节点的val加入到list中。 如果不是的话,继续压入该节点的左右节点。

简单的举例如下:



三、代码:

package T01;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;/** * @author 作者 : xcy * @version 创建时间:2017年1月14日 下午1:14:21 *          类说明 */public class t199 {    public static void main(String[] args) {        // TODO Auto-generated method stub        TreeNode root = new TreeNode(1);        TreeNode t1 = new TreeNode(2);        TreeNode t2 = new TreeNode(3);        TreeNode t3 = new TreeNode(4);        TreeNode t4 = new TreeNode(5);        TreeNode t5 = new TreeNode(6);        TreeNode t6 = new TreeNode(7);        TreeNode t7 = new TreeNode(8);        TreeNode t8 = new TreeNode(9);        TreeNode t9 = new TreeNode(10);        root.left = t1;        root.right = t2;        t1.left = t3;        t1.right = t4;        t2.left = t5;        t2.right = t6;        t3.left = t7;        t3.right = t8;        t4.left = t9;        List<Integer> re = rightSideView(root);        for (int i : re) {            System.out.println(i);        }    }    public static List<Integer> rightSideView(TreeNode root) {        List<Integer> re = new ArrayList<Integer>();        Queue<TreeNode> que = new LinkedList<TreeNode>();        que.add(root);        que.add(null);        while (!que.isEmpty()) {            TreeNode tmp = que.poll();            if (tmp == null) {                if (que.isEmpty()) {                    break;                } else {                    que.add(null);                }            } else {                if (que.peek() == null) {                    re.add(tmp.val);                }                if (tmp.left != null)                    que.add(tmp.left);                if (tmp.right != null)                    que.add(tmp.right);            }        }        return re;    }}

1 0
原创粉丝点击