Topic description:
Please implement a function to determine whether a binary tree is symmetric. Note that a binary tree is symmetric if it is the same as its mirror image.
Analysis:
For a binary tree, traverse from the root node,
if one of the left and right child nodes is NULL, then it is definitely not a symmetric binary tree;
if the left and right child nodes are not empty, but not equal, then it is definitely not a symmetric binary tree;
If the left and right child nodes are not empty and equal, then
traverse left subtree, the traversal order is: current node, left subtree, right subtree;
traverse the right subtree, the traversal order is: current node, right subtree , the left subtree;
if the sequence of traversing the left subtree is the same as the sequence of traversing the right subtree, then the binary tree is a symmetric binary tree. (recursive implementation)
code show as below:
/**
* 对称的二叉树
*/
public class SymmetricalBinaryTree {
public boolean isSymmetrical(TreeNode root) {
return isSymmetrical(root,root);
}
public boolean isSymmetrical(TreeNode root1,TreeNode root2){
//如果两个根节点都是null
if(root1 == null&&root2 == null){
return true;
}
//如果只有一个根节点是null
if(root1 == null || root2 == null){
return false;
}
/**
* 两个根节点都不为null
*/
if(root1.val != root2.val){
return false;
}
return isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right,root2.left);
}
}
//二叉树的定义
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}