🌟坚持每日刷算法,将其变为习惯🤛
题目链接:101. 对称二叉树
最开始肯定是比较简单的想法,就是遍历左右节点呀,不相等我就直接返回false。
但是这样错了,我们要的是以根节点为轴,而不是以各个子节点。
反例:
/*** 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) {if(root == null) return true;isSymmetric(root.left);isSymmetric(root.right);if(root.left == root.right) return true;else return false;}
}
正确做法
- 先排除不能遍历子节点的情况:
// 首先排除空节点的情况if (left == null && right != null) return false;else if (left != null && right == null) return false;else if (left == null && right == null) return true;// 排除了空节点,再排除数值不相同的情况else if (left.val != right.val) return false;
- 再去递归子节点
完整代码如下:
/*** 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 {boolean compare(TreeNode left, TreeNode right){// 首先排除空节点的情况if (left == null && right != null) return false;else if (left != null && right == null) return false;else if (left == null && right == null) return true;// 排除了空节点,再排除数值不相同的情况else if (left.val != right.val) return false;// 如果相同,继续递归逻辑compare(left.left, right.right);compare(left.right, right.left);return compare(left.left, right.right) && compare(left.right, right.left);}public boolean isSymmetric(TreeNode root) {if(root == null) return true;return compare(root.left, root.right);}
}