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

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

寬搜,從右側往左加,分層,將隊列中首個node取val加入list


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
      return bfs(root);
    }
    
    private List<Integer> bfs(TreeNode root){
      if(root==null) return new ArrayList<Integer>();
      Queue<TreeNode> cur = new LinkedList<>();
      Queue<TreeNode> next = new LinkedList<>();
      cur.offer(root);
      List<Integer> res = new ArrayList<>();
      while(!cur.isEmpty()){ 
        res.add(cur.peek().val);
        while(!cur.isEmpty()){
          TreeNode t = cur.poll();
          if(t.right!=null) next.offer(t.right);
          if(t.left!=null) next.offer(t.left);
        }
       
        Queue<TreeNode> tmp = cur;
        cur = next;
        next = tmp;
      }
      return res;
    }
}







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