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.
代码:
/** * 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
- [LeetCode]104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- [LeetCode]104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 【LeetCode】104. Maximum Depth of Binary Tree
- LeetCode#104. Maximum Depth of Binary Tree
- Leetcode 104. Maximum Depth of Binary Tree
- LeetCode *** 104. Maximum Depth of Binary Tree
- net-tools和iproute2
- 在服务器上部署LAMP环境
- android应用安装包大小优化
- C++之RTTI
- 简述JS作用域、作用域链和闭包
- LeetCode 104. Maximum Depth of Binary Tree
- WeX5--单页应用
- POJ1584 A Round Peg in a Ground Hole
- OpenStack 升级实践文章
- hdu2602 Bone Collector 01背包问题
- UWP Windows10开发获取设备位置(经纬度)
- 字符串算法——求最长公共子序列(摘自算法基础,没有代码)
- 专业的个人记帐软件 爱上记帐 1.0.1
- 二叉树的 前中后遍历