Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along, the longest path from the root node to the farthest leaf node.
Hide Tags:tree, Depth-first Search
Title: The maximum depth of the two-fork tree is obtained, and the root node is defined as 1 depth.
Idea: also take recursion
Recursive termination conditions:
A: If root is null, the description is out of bounds and returns depth 0
Determine the direction of the node:
A: If Root is a leaf, if (root->left = = NULL && Root->right = = null) returns depth 1
B: If the node has no left node, that is if (root->left = = NULL), then the recursive return mindepth (root->right) + 1 is executed;
C: If the node has no right node, then return Mindepth (root->left) + 1;
Recursive main process:
int L = mindepth (root->left) + 1;
int r = mindepth (root->right) + 1;
Finally in judging the size of L and R, return the big person return l>r? L:r;
/** * Definition forA binary tree node. * struct TreeNode {*intVal * struct TreeNode * Left; * struct TreeNode * Right; * }; */intMaxDepth (struct treenode* root) {if(Root = =NULL) return0;if(root-> Left==NULL&& root-> Right==NULL) return1;Else if(root-> Left==NULL) Return MaxDepth (root-> Right) +1;Else if(root-> Right==NULL) Return MaxDepth (root-> Left) +1;intL = maxDepth (root-> Left) +1;intR = maxDepth (root-> Right)+1; return l>r?l:r;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Leetcode]-maximum Depth of Binary Tree