1. 程式人生 > 其它 >[LeetCode 中等 二叉樹]199. 二叉樹的右檢視

[LeetCode 中等 二叉樹]199. 二叉樹的右檢視

技術標籤:leetcode

題目描述

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

示例:
輸入: [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> res = new ArrayList<>(); if(root==null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while(!queue.isEmpty()){ int
count = queue.size(); while(count>0){ TreeNode cur = queue.remove(); if(count==1) res.add(cur.val); if(cur.left != null) queue.offer(cur.left); if(cur.right != null) queue.offer(cur.right); count--; }
} return res; } }

深度優先搜尋

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> res = new ArrayList<>();
    
    public List<Integer> rightSideView(TreeNode root) {
        recursion(root,0);
        return res;
    }

    public void recursion(TreeNode root,int depth){
        if(root == null) return ;
        if(res.size() == depth) res.add(root.val);
        depth++;
        recursion(root.right,depth);
        recursion(root.left,depth);
    }
}