leetcode 102 Binary Tree Level Order Traversal(DFS||BFS)

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]
]

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > levelOrder(TreeNode* root) {
        if(root == NULL){
            vector<vector<int> >ans(0);
            return ans;
        }
        
        queue<pair<TreeNode*,int> >q;
        q.push(make_pair(root,0));
        
        vector<vector<int> >ans;
        
        while(!q.empty()){
            TreeNode* t=q.front().first;
            int depth=q.front().second;
            
            if(ans.size()==depth){
                ans.push_back(vector<int>());
            }
            
            ans[depth].push_back(t->val);
            
            if(t->left!=NULL){
                q.push(make_pair(t->left,depth+1));
            }
            if(t->right!=NULL){
                q.push(make_pair(t->right,depth+1));
            }
            q.pop();
        }
        
        return ans;
        
    }
};
BFS法
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> >ans;

    void dfs(TreeNode* r,int depth){
        if(r==NULL) return ;
        
        if(ans.size()==depth){
            ans.push_back(vector<int>());
        }
        ans[depth].push_back(r->val);
        
        dfs(r->left,depth+1);
        dfs(r->right,depth+1);
    }

    vector<vector<int> > levelOrder(TreeNode* root) {
        dfs(root,0);
        return ans;
    }
        
};
DFS法

 

posted @ 2016-02-26 17:59  周洋  阅读(264)  评论(0编辑  收藏  举报