如何检查BST的结构是否对称

时间:2017-03-28 00:20:35

标签: java binary-search-tree symmetric

我正在编写程序,我需要知道BST的结构是否对称

public void traverse (Layer root){     

     if (root.leftChild != null){ 
         traverse (root.leftChild);           
     }
     if (root.rightChild != null){
         traverse (root.rightChild);
     }

我有遍历代码,但我不知道如何检查它是否是对称的

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

我在学校学会了如何做到这一点,这就是我的所作所为。我是从一个我不记得的网站上学到的,但我把评论保留在其中。

boolean isMirror(Node node1, Node node2) 
    {
        // if both trees are empty, then they are mirror image
        if (node1 == null && node2 == null)
            return true;

        // For two trees to be mirror images, the following three
        // conditions must be true
        // 1 - Their root node's key must be same
        // 2 - left subtree of left tree and right subtree
        //      of right tree have to be mirror images
        // 3 - right subtree of left tree and left subtree
        //      of right tree have to be mirror images
        if (node1 != null && node2 != null && node1.key == node2.key)
            return (isMirror(node1.left, node2.right)
                    && isMirror(node1.right, node2.left));

        // if neither of the above conditions is true then
        // root1 and root2 are mirror images
        return false;
    }
boolean isSymmetric(Node node) 
    {
        // check if tree is mirror of itself
        return isMirror(node, node);
    }

答案 1 :(得分:0)

public boolean isSymmetric(Layer root) {
    return root == null || isSymmetric(root.left, root.right);
}

public boolean isSymmetric(Layer left, Layer right) {
    if (left == null && right == null) return true;
    return left != null && right != null && left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
}

我想你的意思是,如果树形成了自己的“镜子”,那么树是对称的