Binary Tree Level Order Traversal -- LeetCode

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

思路:dfs。这里要注意的是,vector数组的size函数返回值是unsigned int类型。因此,语句res.size() - 1 < 0 就会因为溢出变成最大值从而变成false。

 1 class Solution {
 2 public:
 3     void help(vector<vector<int> >& res, TreeNode* root, int depth)
 4     {
 5         if (root == NULL) return;
 6         if (res.size() < depth + 1)
 7         {
 8             vector<int> tem;
 9             res.push_back(tem);
10         }
11         res[depth].push_back(root->val);
12         help(res, root->left, depth + 1);
13         help(res, root->right, depth + 1);
14     }
15     vector<vector<int>> levelOrder(TreeNode* root) {
16         vector<vector<int> > res;
17         help(res, root, 0);
18         return res;
19     }
20 };

 

posted @ 2016-01-27 06:00  fenshen371  阅读(160)  评论(0编辑  收藏  举报