二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明:叶子节点是指没有子节点的节点。
class Solution{
public int maxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(maxDepth(root.left)+1,maxDepth(root.right)+1);
}
}
对称二叉树
给定一个二叉树,检查它是否是镜像对称的
class Solution{
public boolean isSymmetric(TreeNode root){
if(root == null) return false;
return symmetric(root.left,root.right);
}
public boolean symmetric(TreeNode left,TreeNode right){
if(left == null && right == nulll) return true;
if(left ==null || rigth == null) return false;
return (left.val == right.val)
&& symmetric(left.left,right.right)
&& symmetric(right.left,left.right);
}
}
路径总和
给你二叉树的根节点root和一个表示目标和的整数targetSum,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和targetSum
叶子节点是指没有子节点的节点
class Solution{
public boolean hasPathSUm(TreeNode root,int targetSum){
//判断该树是否为空树
if(root == null) return false;
if(root.left == null && root.right == null){
return root.val == targetSum;
}
return hasPathSUm(root.left,targetSum-root.val) || hasPathSum(root.right,targetSum-root.val);
}
}