102&&107. Binary Tree Level Order Traversal I&&II

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]
]
class Solution {
public:
    vector > res;
public:
    void trval(TreeNode *root,int level)
    {
        if(root==NULL)
            return;
       if(level==res.size())   //这句是关键啊
       {
           vector v;
           res.push_back(v);
       }
       res[level].push_back(root->val);
       trval(root->left,level+1);
       trval(root->right,level+1);
    }
    vector > levelOrder(TreeNode *root) {
        
        trval(root,0);
        return res;
      
        
    }
};

 

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

 

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > res;
    void order(TreeNode *root,int level)
    {
        if(root==NULL)
            return ;
       
        if(res.size()==level)
        {
             vector<int> tmp;
             res.push_back(tmp);
        }
            
        res[level].push_back(root->val);
        order(root->left,level+1);
        order(root->right,level+1);
    }
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        order(root,0);
        return vector<vector<int> > (res.rbegin(),res.rend());    //直接一句话解决了
        
        
    }
};

 

posted @ 2015-05-17 16:23  linqiaozhou  阅读(139)  评论(0编辑  收藏  举报