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;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
101.对称二叉树
题目链接:力扣
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
// 确定递归函数的参数和返回值
public boolean compare(TreeNode left,TreeNode right) {
if (left == null && right != null) {return false;}
if (left != null && right == null) {return false;}
if (left == null && right == null) {return true;}
if (left.val != right.val) {return false;}
// 比较外侧
boolean outside = compare(left.left,right.right); // 左子树的左 右子树的右
// 比较内侧
boolean inside = compare(left.right,right.left); // 左子树的右 右子树的左
// 判断是否互为翻转
return outside && inside; // 根节点 中
}
}