关于leetcode:每日一练27二叉树的深度

8次阅读

共计 1331 个字符,预计需要花费 4 分钟才能阅读完成。


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/probl…

办法一:递归

后续遍历:

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

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;
}
正文完
 0