[Leetcode 199] Binary Tree Right Side View

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.