二叉树的最大深度
- 给定一个二叉树,找出其最大深度。
- 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
这题我的解题思路是层级遍历每一层,遍历到下一层层数i就+1 || 或者是前序遍历,在外部定义一个height 遍历到底部就与height对比
最后发现代码太累赘了根本没写,直接借用别人的代码 出处
public int maxDepth(Node node){
if(node == null){
return 0;
}else {
int left = maxDepth(node.left);
int right = maxDepth(node.right);
return left > right ? (left + 1) : (right + 1);
}
}
对称二叉树
- 给定一个二叉树,检查它是否是镜像对称的。
这题不会做,看看半成品吧
public boolean isSymmetric(){
if (root.left == null && root.right == null){
return true;
}
return isSymmetric(root);
}
private boolean isSymmetric(Node node){
if (node.left == null || node.right == null){
return false;
}
if (node.left.left == null && node.left.right == null && node.right.left == null && node.right.right == null){
return true;
}
Node leftA = node.left.left;
Node rightA = node.right.right;
Node rightB = node.left.right;
Node leftB = node.right.left;
boolean booleanA = false;
boolean booleanB = false;
if (leftA != null && rightA != null && leftA.data == rightA.data){
booleanA = isSymmetric(node.left);
}
if (leftB != null && rightB != null && leftB.data == rightB.data){
booleanB = isSymmetric(node.right);
}
if (!booleanA || !booleanB) {
return false;
}
return true;
}
路径总和
- 给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值 相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false 。
题目没搞明白,但是具体功能已完成(当root只有一个或者root只有左右子树时LeetCode不给过)(当树高度超过3一切正常)
private boolean hasPathSum(Node node,int targetSum,int nowSum){
if (node == null){
return false;
}
if (node.data + nowSum == targetSum){
return true;
}else {
boolean A = hasPathSum(node.left,targetSum,node.data + nowSum);
boolean B = hasPathSum(node.right,targetSum,node.data + nowSum);
if (A == true || B == true){
return true;
}
}
return false;
}
public boolean hasPathSum(int targetSum) {
return hasPathSum(root,targetSum,0);
}