剑指Offer55-二叉树的深度-easy

试题链接

题目描述:

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如输入:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

数据范围:

节点总数 <= 10000

解题思路:

  1. dfs,深度优先搜索。
  2. 搜索顺序 先左子树,再右子树。最后回到此结点,取左右子树的深度最大值再 +1
  3. 递归出口是非叶子结点(NULL),返回即可。

AC代码(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);
    }
};

猜你喜欢

转载自blog.csdn.net/Yang_1998/article/details/113038076