Sword refers to the depth of Offer55-binary tree-easy

Question link

Title description:

Enter the root node of a binary tree and find the depth of the tree. From the root node to the leaf node, the nodes (including the root and leaf nodes) passing through in turn form a path of the tree, and the length of the longest path is the depth of the tree.

For example, enter:

Given a binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

Return its maximum depth 3.

data range:

节点总数 <= 10000

Problem-solving ideas:

  1. dfs, depth first search.
  2. The search order is the left subtree first, then the right subtree. Finally, return to this node, take the maximum depth of the left and right subtrees and +1
  3. The recursive exit is a non-leaf node (NULL), just return.

AC code (c++)

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

Guess you like

Origin blog.csdn.net/Yang_1998/article/details/113038076