199-Binary Tree Right Side View

kevin聰發表於2018-05-06

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.


Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

問題描述

給定二叉樹, 返回以從右邊看的視角所能獲取到的值。


問題分析

BFS或者DFS

DFS使用前序遍歷(與一般的前序遍歷的不同的地方為先從右邊遍歷), 另外注意利用height


解法1

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        // reverse level traversal
        List<Integer> result = new ArrayList();
        if(root == null) return result;

        Queue<TreeNode> queue = new LinkedList();
        queue.offer(root);
        while (queue.size() != 0) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                if (i == 0) result.add(cur.val);
                if (cur.right != null) queue.offer(cur.right);
                if (cur.left != null) queue.offer(cur.left);
            }

        }

        return result;
    }
}

解法2

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> res = new ArrayList();
        if(root == null) return res;

        preorder(root, res, 0);
        return res;
    }
    public void preorder(TreeNode root, List<Integer> res, int height){
        if(root == null) return;

        if(height == res.size())    res.add(root.val);

        preorder(root.right, res, height + 1);
        preorder(root.left, res, height + 1);
    }
}

相關文章