每日一练(27):二叉树的深度


title: 每日一练(27):二叉树的深度

categories:[剑指offer]

tags:[每日一练]

date: 2022/02/26


每日一练(27):二叉树的深度

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

例如:

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

提示:

节点总数 <= 10000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof

方法一:递归

后续遍历:

按照递归三部曲,来看看如何来写。

1.确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
代码如下:

int getDepth(TreeNode* node)

2.确定终止条件:如果为空节点的话,就返回0,表示高度为0。
代码如下:

if (node == NULL) return 0;

3.确定单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。

int leftDepth = getDepth(node->left);       // 左
int rightDepth = getDepth(node->right);     // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
//1简化前
int getDepth(TreeNode *root) {
    if (root == 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);
}
//2简化后
int maxDepth(TreeNode* root) {
    return (root == NULL) ? 0 : 1 + max(maxDepth(root->left), maxDepth(root->right));
}

方法二:迭代法(BFS)

使用迭代法的话,使用层序遍历是最为合适的,因为最大的深度就是二叉树的层数,和层序遍历的方式极其吻合

int maxDepth(TreeNode* root) {
	if (root == NULL) {
        return 0;
    }
    int depth = 0;
    queue<TreeNode*> que;
    que.push(root);
    while (!que.empty()) {
        depth++;
        int size = que.size();
        for (int i = 0; i < size; i++) {
            TreeNode* node = que.front();
            que.pop();
            if (node->left) {
                que.push(node->left);
            }
            if (node->right) {
                que.push(node->right);
            }
        }
    }
    return depth;
}
posted @ 2022-02-26 09:18  hackettt  阅读(33)  评论(0编辑  收藏  举报