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

LeetCode 104. Maximum Depth of Binary Tree

时间:2016-11-03 09:30:34      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:root   入队   public   方法   非递归   null   gray   最大   ber   

Problem:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

初看本题第一印象为递归写法。首先找出终止条件:node == NULL。若未进入递归终止状态,则分左子树和又子树进行递归,最终返回累加最大的值。其代码如下:

/**
 * 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 {
public:
    int maxDepth(TreeNode* root) 
    {
        if(root == NULL)
        {
            return 0;
        }
        int left_node = maxDepth(root->left) + 1;
        int right_node = maxDepth(root->right) + 1;
        return (left_node > right_node)? left_node : right_node;
    }
};

通过参看博客发现,还有非递归解法——通过BFS求解。将一层的节点加入到一个队列中,然后依次出队。每一层入队计数器加1,最后一层加入后即可算出总的深度。参见原博:http://blog.csdn.net/wangyaninglm/article/details/45700837

其代码如下:

方法一:

int maxDepth(TreeNode *root)
{
    if(root == NULL)
        return 0;

    int res = 0;
    queue<TreeNode *> q;
    q.push(root);
    while(!q.empty())
    {
        res++;
        for(int i = 0, n = q.size(); i < n; ++ i)
        {
            TreeNode *p = q.front();
            q.pop();

            if(p -> left != NULL)
                q.push(p -> left);
            if(p -> right != NULL)
                q.push(p -> right);
        }
    }

    return res;
}

方法二:

int maxDepth(TreeNode *root)
{
    if (root == NULL) return 0;
    stack<TreeNode *> gray;
    stack<int> depth;
    int out = 0;

    gray.push(root);
    depth.push(1);
    while (!gray.empty()) {
        TreeNode *tmp = gray.top();
        int num = depth.top();
        gray.pop();
        depth.pop();
        if (tmp->left == NULL && tmp->right == NULL) {
            out = num > out ? num : out;
        }
        else {
            if (tmp->left != NULL) {
                gray.push(tmp->left);
                depth.push(num + 1);
            }
            if (tmp->right != NULL) {
                gray.push(tmp->right);
                depth.push(num + 1);
            }
        }
    }
    return out;
}

 

LeetCode 104. Maximum Depth of Binary Tree

标签:root   入队   public   方法   非递归   null   gray   最大   ber   

原文地址:http://www.cnblogs.com/yrwang/p/6025225.html

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