199Binary Tree Right Side View

来源:互联网 发布:物业收费软件 编辑:程序博客网 时间:2024/06/11 04:37

题目链接:https://leetcode.com/problems/binary-tree-right-side-view/

题目:

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

解题思路:
这题的考点是树的层次遍历的变形。
1. 从右往左看去,能看到的每层的结点就是该层最右的结点,该层其它结点都被最右结点挡住了。
2. 解法就是层次遍历每一层,每一层的最右结点就是要找的结点。
3. 即,使用一个队列存储树的一层结点,将每一层最右结点放到结果链表中。

具体代码实现,采用两个队列,一个队列放上一层的结点,一个队列放当前层的结点。
也可以只采用一个队列,此时只用记住每一层的结点个数,即可将一个队列中的结点切分为父结点层和子结点层。

代码实现:
采用两个队列:

/** * 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) {        List<Integer> res = new ArrayList();        if(root == null)            return res;        LinkedList<TreeNode> father = new LinkedList();        father.add(root);        res.add(root.val);        while(!father.isEmpty()) {            LinkedList<TreeNode> children = new LinkedList();            while(!father.isEmpty()) {                TreeNode r = father.poll();                if(r.left != null)                    children.add(r.left);                if(r.right != null)                    children.add(r.right);            }            if(!children.isEmpty()) {                father = children;                res.add(father.peekLast().val);            }        }        return res;    }}
210 / 210 test cases passed.Status: AcceptedRuntime: 3 ms

只采用一个队列:

/** * 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){            //get size here            int size = queue.size();            for(int i=0; i<size; i++){                TreeNode top = queue.remove();                //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;    }}
210 / 210 test cases passed.Status: AcceptedRuntime: 3 ms
0 0
原创粉丝点击