码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Level Order Traversal -- LeetCode

时间:2016-01-27 07:08:43      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Binary Tree Level Order Traversal -- LeetCode

标签:

原文地址:http://www.cnblogs.com/fenshen371/p/5162040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!