Title Description
Given a binary tree to find its maximum depth.
The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.
Description: leaf node is a node has no child nodes.
Examples
Given a binary tree [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
Return to its maximum depth of 3.
Questions asked
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 int maxDepth(struct TreeNode* root){ 11 12 }
answer
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 10 int _max(int a,int b){ 11 return a>b?a:b; 12 } 13 14 int maxDepth(struct TreeNode* root){ 15 if(root==NULL)return 0; 16 / * 17 plus three lines will be faster, when the small amount of data (high limit) 18 is IF (directory root-> left == NULL && directory root-> right == NULL) return. 1; . 19 the else IF (directory root-> left NULL ==) return maxDepth (directory root-> right) + 1'd; 20 is the else IF (directory root-> right == NULL) return maxDepth (directory root-> left) + 1'd; 21 is * / 22 is return . 1 + _max (maxDepth (the root -> left), maxDepth (directory root-> right)); 23 is }
Sign recursive problem, recursive problem as long as the thoughtful consideration, especially the case of the root node is empty, it should not be wrong.
Topic Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.