二叉樹的層次遍歷 描述 筆記 數據 評測 給出一棵二叉樹,返回其節點值的層次遍歷(逐層從左往右訪問) 您在真實的面試中是否遇到過這個題? Yes 哪家公司問你的這個題? LinkedIn Airbnb Amazon Cryptic Studios Dropbox Epic Systems TinyC ...
給出一棵二叉樹,返回其節點值的層次遍歷(逐層從左往右訪問)
您在真實的面試中是否遇到過這個題? Yes 哪家公司問你的這個題? LinkedIn Airbnb Amazon Cryptic Studios Dropbox Epic Systems TinyCo Hedvig Facebook Google Uber Yelp Apple Yahoo Bloomberg Zenefits Twitter Microsoft Snapchat 感謝您的反饋 樣例給一棵二叉樹 {3,9,20,#,#,15,7}
:
3
/ \
9 20
/ \
15 7
返回他的分層遍歷結果:
[ [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; } };