[Leetcode]-Maximum Depth of Binary Tree, leetcode-maximum
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.
Hide Tags: Tree, Depth-first Search
Question: obtain the maximum depth in a binary tree. The root node is defined as 1 depth.
Idea: recursion is also adopted
Recursive termination conditions:
A: If the root value is NULL, it indicates that the request has exceeded the range. The returned depth is 0.
Determine the node direction:
A: if root is A leaf, if (root-> left = NULL & root-> right = NULL), return depth 1.
B: if the node has no left node, that is, if (root-> left = NULL), execute the recursive return minDepth (root-> right) + 1;
C: If the node does not have the right node, return minDepth (root-> left) + 1;
Recursive main process:
Int l = minDepth (root-> left) + 1;
Int r = minDepth (root-> right) + 1;
Finally, when determining the size of l and r, return the large return l> r? L: r;
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */int maxDepth(struct TreeNode* root) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; else if(root->left == NULL) return maxDepth(root->right) + 1; else if(root->right== NULL) return maxDepth(root->left ) + 1; int l = maxDepth(root->left) + 1; int r = maxDepth(root->right)+ 1; return l>r?l:r;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.