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

LeetCode "Binary Tree Level Order Traversal II" using DFS

时间:2016-06-05 11:04:40      阅读:112      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!