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

【解析】

題意:給定一棵二叉樹,返回從右邊看這棵二叉樹所看到的節點序列(從上到下)。

思路:層次遍歷法。遍歷到每層最後一個節點時,把其放到結果集中。

【Java代碼】

public class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans = new ArrayList<Integer>();
        if (root == null) return ans;
        
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        queue.add(null);
        
        while (!queue.isEmpty()) {
            TreeNode node = queue.pollFirst();
            
            if (node == null) {
                if (queue.isEmpty()) {
                    break;
                } else {
                    queue.add(null);
                }
            } else {
                // add the rightest to the answer
                if (queue.peek() == null) {
                    ans.add(node.val);
                }
                
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        
        return ans;
    }
}


發佈了128 篇原創文章 · 獲贊 15 · 訪問量 77萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章