199. 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.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4] Explanation: 1 <--- / \ 2 3 <--- \ \ 5 4 <---
Approach #1: C++. [recursive]
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> rightSideView(TreeNode* root) { vector<int> ans; helper(root, ans, 1); return ans; } private: void helper(TreeNode* root, vector<int>& ans, int level) { if (root == NULL) return; if (ans.size() < level) ans.push_back(root->val); helper(root->right, ans, level+1); helper(root->left, ans, level+1); } };
Approach #2: Java. [bfs + queue]
/** * 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(); Queue<TreeNode> queue = new LinkedList(); if (root == null) return res; queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; ++i) { TreeNode cur = queue.poll(); if (i == 0) res.add(cur.val); if (cur.right != null) queue.offer(cur.right); if (cur.left != null) queue.offer(cur.left); } } return res; } }
Approach #3: Python. [Iterator]
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def rightSideView(self, root): """ :type root: TreeNode :rtype: List[int] """ view = [] if root: level = [root] while level: view += level[-1].val, level = [kid for node in level for kid in (node.left, node.right) if kid] return view
永远渴望,大智若愚(stay hungry, stay foolish)