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
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class BTRightSideView {public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.right = new TreeNode(5);root.right.right = new TreeNode(4);List<Integer> view = rightSideView(root);System.out.println(Arrays.asList(view));}static List<Integer> rightSideView(TreeNode root) {List<Integer> res = new ArrayList<Integer>();if (root == null)return res;Queue<TreeNode> q = new LinkedList<TreeNode>();q.add(root);while (!q.isEmpty()) {int len = q.size();List<Integer> x = new ArrayList<Integer>();while (len > 0) {len--;root = q.poll();x.add(root.val);if (root.left != null)q.add(root.left);if (root.right != null)q.add(root.right);}res.add(x.get(x.size() - 1));}return res;}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data = data;this->left = NULL;this->right = NULL;}};vector<int> rightSideView(TreeNode *root){vector<int> res;if (root == NULL)return res;queue<TreeNode *> q;q.push(root);while (!q.empty()){int len = q.size();vector<int> x;while (len--){root = q.front();q.pop();x.push_back(root->data);if (root->left)q.push(root->left);if (root->right)q.push(root->right);}res.push_back(x[x.size() - 1]);}return res;}int main(){TreeNode *root = new TreeNode(1);root->left = new TreeNode(2);root->right = new TreeNode(3);root->left->right = new TreeNode(5);root->right->right = new TreeNode(4);vector<int> view = rightSideView(root);cout << "[";for (int i = 0; i < view.size() - 1; i++)cout << view[i] << ", ";cout << view[view.size() - 1] << "]";return 0;}
No comments:
Post a Comment