LeetCode 104. Maximum Depth of Binary Tree

来源:互联网 发布:nginx conf 配置 编辑:程序博客网 时间:2024/06/06 00:56

题目链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/?tab=Description

题目描述:


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.


思路一:一开始自己的思路就是DFS遍历,更新路径的最大深度,代码不够简洁

代码:

/** * 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) {        int result=0;        DFS(root,result,0);        return result;    }    void DFS(TreeNode* root,int &maxn,int n)    {        if(root==NULL)        {            if(maxn<n)                maxn=n;            return;        }        n++;        DFS(root->left,maxn,n);        DFS(root->right,maxn,n);    }};


思路二:用DFS回溯到的当前节点的最大深度,等于它的左右子树中的最大深度加1,代码很简洁

代码:

/** * 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 depth1=maxDepth(root->left);        int depth2=maxDepth(root->right);        return depth1>depth2?depth1+1:depth2+1;     }};


0 0
原创粉丝点击