two maximum depth of the fork tree
Given a binary tree, find its maximum depth.
The depth of the binary tree is the distance from the root node to the farthest leaf node.
If the binary tree is empty, the depth is 0
If not empty, respectively, the depth of the left subtree and the right sub-tree depth, go to the largest plus 1, because the root node depth is 1, to add in.
int*root) { //write your code (here) if(root == NULL) return0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return11); }
two minimum depth of the fork tree
Given a binary tree, find its minimum depth.
The minimum depth of the binary tree is the distance from the root node to the nearest leaf node.
Just start to get this problem, think is not very simple, not the maximum depth of the code to be the smallest? The result of this is that some tests do not pass.
Because if there is a case of oblique tree, that is, only left dial hand tree, or only the right subtree, if according to the algorithm just said, the answer is 0, obviously wrong.
Two implementation methods, one is to calculate the Saozi right subtree depth when the judgment is equal to 0, if equal to 0, that the subtree does not exist, the depth assignment is the maximum value.
The second is to determine whether the left or right subtree is empty, if the left subtree is empty, then returns the depth of the right subtree, and conversely returns the depth of the left subtree, if not NULL, returns the minimum value of the Saozi right subtree depth.
int Mindepth (TreeNode*Root) {//Write your code here if(Root== NULL)return false;if(Root -Left== NULL &&Root -Right== NULL)return 1; int leftdepth=Mindepth (Root -left);if(leftdepth== 0) leftdepth=Int_max; int rightdepth=Mindepth (Root -right);if(rightdepth== 0) rightdepth=Int_max;returnLeftdepth<Rightdepth?(leftdepth+ 1): (rightdepth+ 1); }
int Mindepth (TreeNode*Root) {//Write your code here if(Root== NULL)return false;if(Root -Left== NULL)returnMindepth (Root -Right+ 1;if(Root -Right== NULL)returnMindepth (Root -Left+ 1; int leftdepth=Mindepth (Root -left); int rightdepth=Mindepth (Root -right);returnLeftdepth<Rightdepth?(leftdepth+ 1): (rightdepth+ 1); }
(Maximum) Depth of Binary Tree
http://www.lintcode.com/zh-cn/problem/maximum-depth-of-binary-tree/
(155) Minimum Depth of Binary Tree
http://www.lintcode.com/zh-cn/problem/minimum-depth-of-binary-tree/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Maximum depth and minimum depth of binary tree