[Leetcode]199.binary Tree Right Side View

Source: Internet
Author: User

Topic

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,
1 <-
/ \
2 3 <-
\ \
5 4 <-
You should return [1, 3, 4].

Ideas

Hierarchical traversal

Code

    /*-------------------------------------------------------------------* Date: 2014-04-05 * SJF0115 * Title: 1 99.Binary Tree Right Side View * Source: https://leetcode.com/problems/binary-tree-right-side-view/* Result: AC * source : Leetcode * Summary:--------------------------------------------------------------------*/    #include <iostream>    #include <vector>    #include <queue>    using namespace STD;structtreenode{intVal        TreeNode *left;        TreeNode *right; TreeNode (intx): Val (x), left (null), right (null) {}};classSolution { Public: vector<int>Rightsideview (TreeNode *root) { vector<int>Resultif(Root = =nullptr){returnResult }//if             queue<TreeNode*>Cur queue<TreeNode*>Next            Cur.push (root);            Result.push_back (Root->val); TreeNode *node,*pre;//Hierarchical Traversal             while(!cur.empty ()) {pre =nullptr; while(!cur.empty ())                    {node = Cur.front (); Cur.pop ();if(Node->left)                        {Next.push (node->left);                    Pre = node->left; }//if                    if(Node->right)                        {Next.push (node->right);                    Pre = node->right; }//if}//while                if(Pre! =nullptr) {Result.push_back (pre->val); }//ifSwap (Cur,next); }//while            returnResult }    };intMain () {solution solution; TreeNode *root =NewTreeNode (1); Root->left =NewTreeNode (2); Root->right =NewTreeNode (3); Root->left->right =NewTreeNode (5); Root->right->right =NewTreeNode (4); vector<int>result = Solution.rightsideview (root); for(inti =0; i < result.size (); ++i) {cout<<result[i]<<" "; }//for    cout<<endl;return 0;}

Run time

[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.