Article Directory
28 is inscribed: symmetrical binary tree
I. Description of the problem
Please implement a function, a binary tree is used to determine not symmetrical. If a binary tree and its image, as it is symmetrical.
Tree as follows:
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
The figure, A is not symmetrical BC
Second, the problem analysis
Direct comparison to the root, we focus on analysis about sub-tree.
Symmetrical binary tree to meet the above example, it can be seen, the left and right subtrees also happens to be a mirror image of two binary tree
when comparing we
can use a left subtree of the parent node -> the left node -> the right node traversal mode - 657
of right subtree of the parent node can be used -> right node -> the left node traversal mode - 657
according to the comparison sequence.
Third, questions
public boolean isSymmetrical(TreeNode pRoot){
if(pRoot==null) {
return true; //根结点为null时,认为是对称二叉树
}
return isEqual(pRoot.left,pRoot.right);
}
private boolean isEqual(TreeNode pRoot1,TreeNode pRoot2){
if(pRoot1==null && pRoot2==null) {
return true;
}
if(pRoot1==null || pRoot2==null) {
return false;
}
return pRoot1.val==pRoot2.val
&& isEqual(pRoot1.left, pRoot2.right)
&& isEqual(pRoot1.right, pRoot2.left);
}