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; }};