Sword refers to Offer 28 (tree 4). Symmetrical binary tree
Problem Description:
Please implement a function to judge whether a binary tree is symmetric. A binary tree is symmetric if it is the same as its mirror image.
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
example:
输入:root = [1,2,2,3,4,4,3] 输出:true
输入:root = [1,2,2,null,3,null,3] 输出:false
Problem-solving ideas:Idea link
- Symmetric binary tree definition: For any two symmetrical nodes L and R in the tree, there must be:
- L.val = R.val : That is, the values of the two symmetrical nodes are equal.
- L.left.val = R.right.val: the left child node of L and the right child node of R are symmetrical;
- L.right.val = R.left.val : That is, the right child node of L and the left child node of R are symmetrical.
According to the above rules, consider recursion from top to bottom to judge whether each pair of nodes is symmetrical, so as to judge whether the tree is a symmetrical binary tree.
Implemented using recursive code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
//当根节点为空时,毫无疑问左右子节点都为null,是对称的
if(root == null){
return true;
}
//建立一个队列,将根节点root放入队列中,并取出根节点,获取根节点的左右子节点
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
TreeNode node = queue.poll();
//递归调用判断左右结点的值是否满足对称
return recursion(node.left,node.right);
}
private static boolean recursion(TreeNode l ,TreeNode r){
//当左右结点的值都为空时,代表同时比较完成,满足对称
if(l == null && r == null){
return true;
}
//判断左右子节点,有一方先判定结束,或者左右子节点的值不同,不满足对称
if(l == null || r == null || l.val != r.val){
return false;
}
//经过以上条件,代表此时左右子节点对应的值相同,递归调用下一个左右子节点的值是否满足对称
boolean t = recursion(l.left,r.right) && recursion(l.right,r.left);
return t;
}
}