[Leetcode]-Maximum Depth of Binary Tree, leetcode-maximum

Source: Internet
Author: User

[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.

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.