Binary Tree Level Order Traversal II [LeetCode]

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

BFS solution:

 1     vector<vector<int> > levelOrderBottom(TreeNode *root) {
 2         vector<vector<int> > ret;
 3         if(root == NULL)
 4             return ret;
 5         vector<TreeNode *> level;
 6         level.push_back(root);
 7         while(true) {
 8             if(level.size() == 0)
 9                 break;
10             vector<int> nums;
11             vector<TreeNode *> tmp;  
12             for(auto item : level) {
13                 nums.push_back(item->val);
14                 if(item->left != NULL)
15                     tmp.push_back(item->left);
16                 if(item->right != NULL)
17                     tmp.push_back(item->right);
18             }
19             ret.insert(ret.begin(), nums);
20             level = tmp;
21         }
22         return ret;
23     }

DFS solution:

 1     void getLevelNums(TreeNode *root, vector<vector<int> > &ret, int level) {
 2         if(ret.size() < level + 1){
 3             vector<int> nums; 
 4             nums.push_back(root->val);
 5             ret.insert(ret.begin(), nums);
 6         }else if (ret.size() >= level + 1) {
 7             ret[ret.size() - level - 1].push_back(root->val);
 8         }
 9 
10         if(root->left != NULL)
11             getLevelNums(root->left, ret, level + 1);
12 
13         if(root->right != NULL)
14             getLevelNums(root->right, ret, level + 1);
15         
16     }
17     vector<vector<int> > levelOrderBottom(TreeNode *root) {
18         vector<vector<int> > ret;
19         if(root == NULL)
20             return ret;
21         getLevelNums(root, ret, 0);
22         return ret;
23     }

 

posted @ 2013-11-12 12:46  假日笛声  阅读(527)  评论(0编辑  收藏  举报