乐观学习,乐观生活,才能不断前进啊!!!
我的主页:optimistic_chen
我的专栏:c语言 ,Java
欢迎大家访问~
创作不易,大佬们点赞鼓励下吧~
文章目录
- 相同的树
- 另一颗树的子树
- 翻转二叉树
- 对称二叉树
- 平衡二叉树
相同的树
相同的树—力扣
class Solution {public boolean isSameTree(TreeNode p, TreeNode q) {//1.判断结构是否一样if(p!=null&&q==null || p==null&&q!=null){return false;}//要么都为null 要么都不为nullif(p==null&&q==null){return true;}//2.判断值是否一样if(p.val!=q.val){return false;}//值一样(左子树与左子树比较)return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);}
}
另一颗树的子树
另一颗树的子树—力扣
class Solution {public boolean isSubtree(TreeNode root, TreeNode subRoot) {//当前子树是否和根结点一样if(root==null){return false;}if(isSameTree(root,subRoot)){return true; }if(isSubtree(root.left,subRoot)){return true;}if(isSubtree(root.right,subRoot)){return true;}return false;}public boolean isSameTree(TreeNode p, TreeNode q) {//1.判断结构是否一样if(p!=null&&q==null || p==null&&q!=null){return false;}//要么都为null 要么都不为nullif(p==null&&q==null){return true;}//2.判断值是否一样if(p.val!=q.val){return false;}//值一样(左子树与左子树比较)return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);}
}
翻转二叉树
翻转二叉树— 力扣
class Solution {public TreeNode invertTree(TreeNode root) {if(root==null){return null;}TreeNode tmp=root.left;root.left=root.right;root.right=tmp;invertTree(root.left);invertTree(root.right); return root;}
}
对称二叉树
对称二叉树—力扣
class Solution {public boolean isSymmetric(TreeNode root) {if(root==null){return true;}return isSymmetricChild(root.left,root.right);}public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){//左树不为空并且右树为空 或者 左树为空右树不为空if(leftTree!=null&&rightTree==null||leftTree==null&&rightTree!=null){return false;}//左树为空并且右树为空if(leftTree==null&&rightTree==null){return true;}//左树的值不等于右树的值if(leftTree.val!=rightTree.val){return false;}//返回左树的左结点 右树的右结点 并且 左树的右结点 右树的左结点return isSymmetricChild(leftTree.left,rightTree.right)&&isSymmetricChild(leftTree.right,rightTree.left);}}
平衡二叉树
平衡二叉树—力扣
class Solution {public boolean isBalanced(TreeNode root) {//如果一棵树是平衡二叉树 那么他的每颗子树都是平衡二叉树(左右子树高度差<=1)if(root==null) return true;return getHright(root)>=0;}public int getHright(TreeNode root){if(root==null){return 0;}int leftHeight=getHright(root.left);if(leftHeight<0){return -1;}int rightHeight=getHright(root.right);//绝对值if(rightHeight>=0&&Math.abs(leftHeight-rightHeight)<=1){return Math.max(leftHeight,rightHeight)+1;}else{return -1;}}
}