代码随想录算法刷题训练营day15:LeetCode(226)翻转二叉树、LeetCode(101)对称二叉树
LeetCode(226)翻转二叉树
题目
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return root;
}
swap(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
public void swap(TreeNode root){
TreeNode temp=root.left;
root.left=root.right;
root.right=temp;
}
}
LeetCode(101)对称二叉树
题目
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//做一个交换的递归
boolean result=compare(root.left,root.right);
return result;
}
public boolean compare(TreeNode left,TreeNode right){
if(left==null&&right==null){
return true;
}else if(left!=null&&right==null){
return false;
}else if(left==null&&right!=null){
return false;
}else if(left!=null&&right!=null&&left.val!=right.val){
return false;
}else{
//两个节点对称----考虑比较外侧和内测的元素
//比较外侧
boolean result1=compare(left.left, right.right);
//比较内测
boolean result2=compare(left.right, right.left);
return result1&&result2;
}
}
}