首页 > 其他 > 详细

LeetCode "Binary Tree Level Order Traversal II" using DFS

时间:2016-06-05 11:01:50      阅读:137      评论:0      收藏:0      [点我收藏+]

BFS solution is intuitive - here I will show a DFS based solution:

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

LeetCode "Binary Tree Level Order Traversal II" using DFS

原文:http://www.cnblogs.com/tonix/p/5560174.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!