104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions

来源:互联网 发布:淘宝3个月没卖出一件 编辑:程序博客网 时间:2024/05/16 18:04

题目

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.


翻译

给定一个二叉树,找到其最大深度。

最大深度是从根节点到最远叶节点的最长路径中的节点数。


分析

之前在刷链表的时候有过类似的题,也是递归的方法

思索片刻后写出了如下代码

/** * 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 buildmax(TreeNode* root,int m){        if(root==NULL)  return m;        if(root->left==NULL||root->right==NULL)   return m+1;        m=max(m,buildmax(root->left,m+1),buildmax(root->right,m+1));        return m;    }         int maxDepth(TreeNode* root) {        int x=buildmax(root,0);        return x;    }};



结果报错,

required from here

查询后才知道max min函数不能直接对三个使用,

错误示范:max(a,b,c),

正确示范:max(a,max(b,c)).


然后去答案区学习大神的代码后,男默女泪


Only one line code.

int maxDepth(TreeNode *root){    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;}
后附带大神的最大宽度代码

Calculate the count of the last level.

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


0 0
原创粉丝点击