首页 > 其他分享 >代码随想录Day20

代码随想录Day20

时间:2022-11-09 01:22:07浏览次数:38  
标签:node getdepth return int 代码 随想录 Day20 root 节点

LeetCode104.找出二叉树最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

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

 

 

 

 返回它的最大深度 3 。

 

深度和高度:

深度是根节点到叶子结点的距离。

高度是叶子节点到根节点的距离。

 

遍历顺序的选取:

高度:左右中(后续遍历)把叶子节点的结果不断返回给根节点。

深度:中左右(前序遍历)从根节点往下遍历。

 

思路:本题求最大深度,其实就是求根节点的高度,根节点的高度就是最大深度。也可以用前序遍历去求。

代码:

class solution {
public:
    int getdepth(treenode* node) {
        if (node == NULL) return 0;
        int leftdepth = getdepth(node->left);       // 左
        int rightdepth = getdepth(node->right);     // 右
        int depth = 1 + max(leftdepth, rightdepth); // 中
        return depth;
    }
    int maxdepth(treenode* root) {
        return getdepth(root);
    }
};

精简版本:

class solution {
public:
    int maxdepth(treenode* root) {
        if (root == null) return 0;
        return 1 + max(maxdepth(root->left), maxdepth(root->right));
    }
};

前序遍历:真正求深度的基本方法。

class solution {
public:
    int result;
    void getdepth(treenode* node, int depth) {
        result = depth > result ? depth : result; // 中
        if (node->left == NULL && node->right == NULL) return ;
        if (node->left) { // 左
            getdepth(node->left, depth + 1);
        }
        if (node->right) { // 右
            getdepth(node->right, depth + 1);
        }
        return ;
    }
    int maxdepth(treenode* root) {
        result = 0;
        if (root == 0) return result;
        getdepth(root, 1);
        return result;
    }
};

 

标签:node,getdepth,return,int,代码,随想录,Day20,root,节点
From: https://www.cnblogs.com/dwj-ngu/p/16871847.html

相关文章