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,node
1 <--- / \ 2 3 <--- \ \ 5 4 <---
You should return [1, 3, 4].算法
給定一個二叉樹,想象本身站在樹的右邊,返回從下到下你能看到的節點的值。ide
二叉樹的層次遍歷,每層按照從左向右的順序依次訪問節點,(每一層取最右邊的結點)spa
樹結點類.net
public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
算法實現類code
public class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new LinkedList<>(); if (root != null) { Deque<TreeNode> deque = new LinkedList<>(); // 當前層的結點數 int current = 1; // 下一層的結點數 int next = 0; TreeNode node; deque.addLast(root); while (deque.size() > 0) { // 取第一個結點 node = deque.removeFirst(); current--; // 添加非空的左結點 if (node.left != null) { next++; deque.addLast(node.left); } // 添加非空的右結點 if (node.right != null) { next++; deque.addLast(node.right); } // 若是當前層已經處理完了 if (current == 0) { // 保存此層的最右一個結點值 result.add(node.val); // 設置下一層的元素個數 current = next; next = 0; } } } return result; } }