101. Symmetric Tree 101.对称树
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
怎么判断左右节点是否为空?
复习时还不会的地方:先判断node12自己是否为空,再递归它们的左右
典型的因为是形状而递归(recursive)的题目。所以最好写个helper函数吧,更加方便表达。之后的参数可以事无巨细地传进去。这题的递归入口
就是左边、右边这样
这种可能是空,不一定有的节点,需要丢到递归函数中。其实这是divide的一部分,只是没有等号罢了。conquer也是一样的具体实现。
//推测着写。
if ((root.left.left.val != root.right.right.val) || (root.left.right.val != root.right.left.val))
参数最好用root1 root2吧,以免混淆
参数可以直接是root1 root2两个陌生节点,而不是root。
所以最后一步就只需要一层root1.left,表示起来更方便
if (root1.val != root2.val)
return false;
//只需要返回false的情况,true的情况需要divide后长期考察才行

/**
* 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;
return helper(root.left, root.right);
}
public boolean helper(TreeNode root1, TreeNode root2) {
if ((root1 == null) && (root2 == null))
return true;
//只有一个为空
if ((root1 == null) || (root2 == null))
return false;
//本身左右不相等
if (root1.val != root2.val)
return false;
//递归的情况
return (helper(root1.left, root2.right) && helper(root1.right, root2.left));
}
}