[Leetcode]-maximum Depth of Binary Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.