【LeetCode】199.Binary Tree Right Side View(Medium)解題報告

【LeetCode】199.Binary Tree Right Side View(Medium)解題報告

題目地址:https://leetcode.com/problems/binary-tree-right-side-view/description/
題目描述:

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

Solution1:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 time : O(n)
 space : O(n)
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null) return res;
        helper(res , root , 0);
        return res;
    }
    public void helper(List<Integer> res,TreeNode root,int level){
        if(root == null) return;
        if(res.size() == level){
            res.add(root.val);
        }
        helper(res,root.right,level+1);
        helper(res,root.left,level+1);
    }
}

Solution2:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 time : O(n)
 space : O(n)
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0 ; i<size ; i++){
                TreeNode cur = queue.poll();
                if(i == 0) res.add(cur.val);
                if(cur.right!=null) queue.offer(cur.right);
                if(cur.left!=null) queue.offer(cur.left);
            }
        }
        return res;
    }
}

Date:2018年3月17日

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章