Leetcode 199 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.

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

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

层次分析变形

根据题目分析,right side view 所看到的结点即每一层最右侧的结点,因而通过层次遍历依次遍历所有层次,并且找到最右边的点。

BFS提交代码(>73.49%)

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        List<TreeNode> queue = new ArrayList<>();
        if (root==null) return result;
        queue.add(root);
        while (!queue.isEmpty()){
            int num = queue.size();
            result.add(queue.get(num-1).val);
            for (int i=0;i<num;i++){
                TreeNode node = queue.remove(0);
                if (node.left!=null) queue.add(node.left);
                if (node.right!=null) queue.add(node.right);
            }
        }
        return result;
    }
}


Leave a Reply

Your email address will not be published. Required fields are marked *