2

I'm coding a program and i need to know if a BST is symmetric in its structure

public void traverse (Layer root){     

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

I have the traverse code but i dont know how to check if it is symmetric

Thanks for the help

  • You'd want to return a boolean value, for starters. This code doesn't seem to do anything special and will throw an exception when `root == null` – OneCricketeer Mar 28 '17 at 00:41
  • Possible duplicate of [Check if a binary tree is a mirror image or symmetric](http://stackoverflow.com/questions/8436623/check-if-a-binary-tree-is-a-mirror-image-or-symmetric) – OneCricketeer Mar 28 '17 at 00:43

2 Answers2

2

I learned how to do this during school, and this is what I did. I learned it from a website I can't remember, but I kept the comments in it.

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);
    }
sbowde4
  • 767
  • 1
  • 4
  • 23
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);
}

I suppose that you mean that tree is symmetric if it is form a "mirror" of itself

wbars
  • 525
  • 6
  • 13