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

LeetCode "Find Leaves of Binary Tree"

时间:2016-06-27 12:04:56      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Typical DFS problem. Simply get higher height and push_back.

/**
 * 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 {
    vector<vector<int>> ret;
    int go(TreeNode *p) // return max height
    {
        if(!p) return 0;
        
        int hl = go(p->left);
        int hr = go(p->right);
        
        int h = max(hl, hr) + 1;
        if(h > ret.size()) ret.push_back({});
        ret[h - 1].push_back(p->val);
        
        return h;
    }
public:
    vector<vector<int>> findLeaves(TreeNode* root) {
        go(root);
        return ret;
    }
};

LeetCode "Find Leaves of Binary Tree"

标签:

原文地址:http://www.cnblogs.com/tonix/p/5619696.html

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