LillianEom
6/19/2018 - 1:04 PM

判断二叉树是否对称

前序遍历:根结点->左结点->右结点 对称前序遍历:根结点->右结点->左结点 比较前序遍历 and 对称前序遍历的序列判断二叉树是否是对称的。

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class SymmetricalBinaryTree {
    boolean isSymmetrical(TreeNode pRoot)
    {
        return isSymmetrical(pRoot, pRoot);
    }
    boolean isSymmetrical(TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null) {
            return true;
        } else if(root1 != null && root2 != null) {
            return (root1.val == root2.val) && isSymmetrical(root1.left, root2.right) && isSymmetrical(root1.right, root2.left);
        } else {
            return false;
        }
    }
}