LeetCode Binary Tree Level Order Traversal

class Solution {
private:
    vector<vector<int> > nodes;
public:
    vector<vector<int> > levelOrder(TreeNode *root) {
        nodes.clear();
        dfs(root, 0);
        return nodes;
    }
    
    void dfs(TreeNode* root, int level) {
        if (root == NULL) return;
        if (level >= nodes.size()) {
            nodes.push_back(vector<int>());
        }
        nodes[level].push_back(root->val);
        dfs(root->left, level + 1);
        dfs(root->right, level + 1);
    }
};

水一发

第二轮:

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]
]
 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> > levelOrder(TreeNode *root) {
13         vector<vector<int> > res;
14         //dfs(res, root, 0);
15         bfs(res, root);
16         return res;
17     }
18     void dfs(vector<vector<int> >& res, TreeNode* root, int level) {
19         if (root == NULL) {
20             return;
21         }
22         if (level == res.size()) {
23             res.push_back(vector<int>());
24         }
25         res[level].push_back(root->val);
26         dfs(res, root->left, level + 1);
27         dfs(res, root->right, level + 1);
28     }
29     
30     void bfs(vector<vector<int> >& res, TreeNode* root) {
31         if (root == NULL) {
32             return;
33         }
34 
35         
36         queue<TreeNode*> que;
37         que.push(root);
38         
39         while (!que.empty()) {
40             int n = que.size();
41             vector<int> current;
42             for (int i=0; i<n; i++) {
43                 TreeNode* node = que.front();
44                 que.pop();
45                 if (node == NULL) {
46                     continue;
47                 }
48                 current.push_back(node->val);
49                 if (node->left != NULL) {
50                     que.push(node->left);
51                 }
52                 if (node->right != NULL) {
53                     que.push(node->right);
54                 }
55             }
56             res.push_back(current);
57         }
58     } 
59 };

 

posted @ 2014-04-25 14:12  卖程序的小歪  阅读(231)  评论(0编辑  收藏  举报