二叉树层序遍历,输出时每一层的节点值要分开存,按第一、二、三...层的顺序
Python版
1 #102
2 #Runtime: 50 ms
3 #Memory Usage: 13.7 MB
4
5 # Definition for a binary tree node.
6 # class TreeNode(object):
7 # def __init__(self, val=0, left=None, right=None):
8 # self.val = val
9 # self.left = left
10 # self.right = right
11 class Solution(object):
12 def levelOrder(self, root):
13 """
14 :type root: TreeNode
15 :rtype: List[List[int]]
16 """
17 if not root:
18 return []
19 q = []
20 ans = []
21 q.append(root)
22 ans.append([root.val])
23 while q:
24 sz = len(q)
25 ans.append([])
26 for i in range(sz):
27 if q[0].left:
28 q.append(q[0].left)
29 ans[-1].append(q[0].left.val)
30 if q[0].right:
31 q.append(q[0].right)
32 ans[-1].append(q[0].right.val)
33 q.pop(0)
34 if not ans[-1]:
35 ans.pop(-1)
36 return ans
CPP版
1 //102
2 //Runtime: 40 ms
3
4 /**
5 * Definition for binary tree
6 * struct TreeNode {
7 * int val;
8 * TreeNode *left;
9 * TreeNode *right;
10 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11 * };
12 */
13 class Solution {
14 public:
15 struct Que {
16 TreeNode *pt;
17 int depth;
18 }que[10010];
19 vector<vector<int> > levelOrder(TreeNode *root) {
20 vector<vector<int> > res;
21 if(root == NULL) return res;
22 int l = 0, r = 1, tdepth = 0;
23 que[0].pt = root;
24 que[0].depth = 0;
25 vector<int> tres;
26 tres.push_back(root->val);
27 res.push_back(tres);
28 tres.clear();
29 while(l < r) {
30 TreeNode *tp = que[l].pt;
31 if(tdepth < que[l].depth) {
32 res.push_back(tres);
33 tres.clear();
34 }
35 if(tp->left != NULL) {
36 que[r].pt = tp->left;
37 que[r].depth = que[l].depth + 1;
38 tres.push_back(tp->left->val);
39 ++r;
40 }
41 if(tp->right != NULL) {
42 que[r].pt = tp->right;
43 que[r].depth = que[l].depth + 1;
44 tres.push_back(tp->right->val);
45 ++r;
46 }
47 tdepth = que[l].depth;
48 ++l;
49 }
50 if(!tres.empty()) res.push_back(tres);
51 return res;
52 }
53 };