Binary Tree Level Order Traversal <leetcode>
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree {3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
算法:本来层次用一个链表就可以了,很容易解决,但是这里的返回结果要求记录每个节点的深度(层),所以用了其他的方法,在网上也查过其他的方法,两个链表也可以解决,这里没有代码,我的代码如下:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<vector<int>> result; 13 vector<vector<int> > levelOrder(TreeNode *root) { 14 result.clear(); 15 doit(root,1); 16 return result; 17 } 18 19 void doit(TreeNode *root,int level) 20 { 21 if(NULL==root) 22 { 23 return; 24 } 25 else 26 { 27 if(level>result.size()) 28 { 29 vector<int> node; 30 result.push_back(node); 31 } 32 result[level-1].push_back(root->val); 33 doit(root->left,level+1); 34 doit(root->right,level+1); 35 } 36 } 37 };