LeetCode Binary Tree Level Order Traversal

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

DFS遍历方法:

 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 private:
12     vector<vector<int> > ret;
13 public:
14     void solve(int dep, TreeNode *root)
15     {
16         if (root == NULL)
17             return;
18             
19         if (ret.size() > dep)
20         {
21             ret[dep].push_back(root->val);
22         }
23         else
24         {
25             vector<int> a;
26             a.push_back(root->val);
27             ret.push_back(a);
28         }
29         
30         solve(dep + 1, root->left);
31         solve(dep + 1, root->right);
32     }
33     
34     vector<vector<int> > levelOrder(TreeNode *root) {
35         // Start typing your C/C++ solution below
36         // DO NOT write int main() function
37         ret.clear();
38         solve(0, root);
39         
40         return ret;
41     }
42 };

 

BFS遍历打印

 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 
11 struct Node
12 {
13     TreeNode *node;
14     int level;
15     Node(){}
16     Node(TreeNode *n, int l):node(n), level(l){}
17 };
18 
19 class Solution {
20 private:
21     vector<vector<int> > ret;
22 public:
23     vector<vector<int> > levelOrder(TreeNode *root) {
24         // Start typing your C/C++ solution below
25         // DO NOT write int main() function
26         ret.clear();
27         
28         if (root == NULL)
29             return ret;
30         
31         queue<Node> q;
32         
33         q.push(Node(root, 0));
34         
35         vector<int> a;
36         int curLevel = -1;
37         
38         while(!q.empty())
39         {
40             Node node = q.front();
41             if (node.node->left)
42                 q.push(Node(node.node->left, node.level + 1));
43             if (node.node->right)
44                 q.push(Node(node.node->right, node.level + 1));
45                 
46             if (curLevel != node.level)
47             {
48                 if (curLevel != -1)
49                     ret.push_back(a);
50                 curLevel = node.level;
51                 a.clear();
52                 a.push_back(node.node->val);                
53             }
54             else
55                 a.push_back(node.node->val);
56                 
57             q.pop();
58         }
59         
60         ret.push_back(a);
61         
62         return ret;
63     }
64 };
posted @ 2012-10-27 22:04  chkkch  阅读(4902)  评论(2编辑  收藏  举报