Title Link: Binary-tree-right-side-view
Import Java.util.arraylist;import java.util.list;/** * Given A binary tree, imagine yourself standing on the right side of It, return the values of the nodes 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]. * */public class Binarytreerightsideview {public class TreeNode {int val; TreeNode left; TreeNode right; TreeNode (int x) {val = x;}} Solution One, the hierarchical traversal method//210/210 test Cases passed.//status:accepted//runtime:300 ms//submitted:0 minutes ago//time complexity O (n), Spatial complexity O ( N) public list<integer> Rightsideview (TreeNode root) {return bfs (root);} Public list<integer> BFS (TreeNode root) {list<integer> result = new arraylist<integer> (); list<treenode> Levelorder = new arraylist<treenode> (); if (root = null) return result; Levelorder.add (root); while (!levelorder.isempty ()) {int Len = Levelorder.size (); Result.add (Levelorder.get (len-1). val); for (int i = 0; i < len; i + +) {TreeNode node = levelorder.remove (0); if (node.left! = null) Levelorder.add (node.left); if (node.right! = null) Levelorder.add (node.right); }} return result; }//Solution Two: Depth traversal method//210/210 test Cases passed.//status:accepted//runtime:229 ms//submitted:0 minute S ago//Time complexity O (n), Space complexity O (n) public list<integer> rightSideView1 (TreeNode root) {list<integer> result = new Arraylist<integer> (); DFS (root, result, 0); return result;} public void Dfs (TreeNode root, list<integer> result, int level) {if (root = null) return; if (level = = Result.size ()) Result.add (Root.val); DFS (root.right, result, level + 1); DFS (Root.left, result, level + 1); } public static void Main (string[] args) {//TODO auto-generated method stub}}
[Leetcode 199] Binary Tree Right Side View