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.
Note: A leaf is a node with no children.
給一棵二元樹,找到它最大深度。
最大深度代表從樹根到最遠樹葉的距離。
提示:樹葉指一個沒有小孩的節點。
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
/**
* 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:
void FindDepth(TreeNode* node, int nowdepth,int &depth)
{
if(!node)return;
depth = max(depth,nowdepth);
FindDepth(node->left,nowdepth+1,depth);
FindDepth(node->right,nowdepth+1,depth);
}
int maxDepth(TreeNode* root) {
int depth=0;
FindDepth(root,1,depth);
return depth;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up