【leetcode】199 二叉樹的右視圖

給定一棵二叉樹,想象自己站在它的右側,按照從頂部到底部的順序,返回從右側所能看到的節點值。

示例:

輸入: [1,2,3,null,5,null,4]
輸出: [1, 3, 4]
解釋:

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

解題思路:剛開始感覺只要輸出右子樹即可,但是在右子樹中還是有擋住的結點,我是用廣搜進行遍歷,個人比較喜歡廣搜,然後每次將最右邊的結點加進去,代碼小技巧,加入隊列的時候先加入最右邊的結點。

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

 

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