[LeetCode] Maximum Depth of Binary Tree

Source: Internet
Author: User

[LeetCode] Maximum Depth of Binary Tree

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.

This question is to find the depth of a binary tree. The definition of depth in the question is: a tree path is formed from the root node to the leaf node (including the root node and leaf node. The length of the longest path is the depth of the tree.

We can obtain all the paths of the tree according to the above definition to get the length of the longest path. However, writing programs in this way is a little troublesome.

We can understand the depth of a tree from one angle: If a tree has only one node, its depth is 1. If the root node has only the left subtree but not the right subtree, the depth of the tree should be the depth of the Left subtree plus 1. Similarly, if the root node has only the right subtree but not the left subtree, the depth of the tree should be the depth of the right subtree plus 1. What if there is both the right subtree and the left subtree? The depth of the tree is that the depth of the left and right sub-trees is greater than the depth of the limit plus 1.

According to the above idea, recursive methods are easy to implement. The following code is attached:

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int maxDepth(TreeNode *root) {        if(root==NULL){            return 0;        }        int left=maxDepth(root->left);        int right=maxDepth(root->right);        return (left>right?left:right)+1;    }};

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.