今天开始继续和大家坚持打卡面试非常重要算法练习---剑指offer,希望我们能一起肝。
1 题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
2 思路1--递归
求树的深度,递归出左右子树的高度,返回较大值即可
3 思路2---迭代(层次遍历)
层次遍历每一层的节点,采用队列作为辅助
4 代码实现
java版本---递归左右
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
//拿到左子树的最大深度
int leftDep = TreeDepth(root.left);
//拿到右子树的最大深度
int rightDep = TreeDepth(root.right);
//找出最大值,并且加上root这一层即可
return Math.max(leftDep,rightDep) + 1;
}
}
c++版本
//author:xiaolan
class Solution {
public:
int TreeDepth(TreeNode* pRoot) {
if (!pRoot) return 0;
queue que;
que.push(pRoot);int depth=0;while (!que.empty()) {int size=que.size();//求得当前队列元素
depth++;for (int i=0;i//一次处理一层的数据
TreeNode *node=que.front();
que.pop();if (node->left) que.push(node->left);if (node->right) que.push(node->right);
}
}return depth;
}
};
py版本--思路和c++的类似
class Solution:
def TreeDepth(self, pRoot):
# edge
if not pRoot:
return 0
return 1 + max(self.TreeDepth(pRoot.left),self.TreeDepth(pRoot.right))
4 动画
5 唠嗑
2020年7月12日打卡,打卡格式"打卡XX天"。暖蓝汇聚大家一起,探讨简历修改,面试经历分享,尽全力让大家能在2020找到理想的工作。如果你想加入,加我拉你进面试交流群。
persist