Lintcode_69 _ hierarchical traversal of a binary tree, lintcode_69 Binary Tree

Source: Internet
Author: User

Lintcode_69 _ hierarchical traversal of a binary tree, lintcode_69 Binary Tree

Layered traversal of Binary Trees

 
  • Description
  • Notes
  • Data
  • Evaluation

Returns the hierarchical traversal of a binary tree's node values (layer-by-layer access from left to right)

Have you ever encountered this question during a real interview? Yes, which company asked you this question? LinkedIn Airbnb Amazon Cryptic Studios Dropbox Epic Systems TinyCo Hedvig Facebook Google Uber Yelp Apple Yahoo Bloomberg Zenefits Twitter Microsoft Snapchat Thank you for your feedback. Example

Give a binary tree{3,9,20,#,#,15,7}:

  3 / \9  20  /  \ 15   7

Returns the result of its layered traversal:

[  [3],  [9,20],  [15,7]]

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /*     * @param root: A Tree     * @return: Level order a list of lists of integer     */    vector<vector<int>> levelOrder(TreeNode * root) {        // write your code here        queue<TreeNode*> q;        vector<vector<int>> ans;        if(root==NULL)            return ans;        int len;        q.push(root);        while(!q.empty())        {            len=q.size();            vector<int> res;            while(len--)            {               TreeNode *p=q.front();               q.pop();               res.push_back(p->val);               if(p->left)                    q.push(p->left);                if(p->right)                    q.push(p->right);                            }            ans.push_back(res);        }        return ans;    }};

  

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.