[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; }};