2017-03-28 2 views
1

ich ein Programm bin Codierung und ich muss wissen, ob ein BST symmetrisch in seiner Struktur istwie kann ich überprüfen, ob ein BST symmetrisch in seiner Struktur ist

public void traverse (Layer root){  

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

ich den Verfahrweg Code haben, aber ich weiß nicht, wie zu überprüfen, ob es symmetrisch

Danke für die Hilfe

+0

Sie möchten einen booleschen Wert für Starter zurückgeben. Dieser Code scheint nichts Besonderes zu tun und wird eine Ausnahme auslösen, wenn 'root == null' –

+0

Mögliche Duplikate von [Überprüfen Sie, ob ein Binärbaum ein Spiegelbild oder symmetrisch ist] (http://stackoverflow.com/questions/ 8436623/check-if-binary-tree-is-a-mirror-image-or-symmetric) –

Antwort

1

Ich habe gelernt, wie man das während der Schule macht, und das habe ich gemacht. Ich habe es von einer Webseite gelernt, an die ich mich nicht erinnern kann, aber ich habe die Kommentare darin behalten.

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

hey danke, es ist einfach zu verstehen –

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); 
} 

ich, dass du diesen Baum bedeuten annehmen ist symmetrisch, wenn sie einen „Spiegel“ von selbst bilden

+0

@ cricket_007 typo :) – wbars

+0

Ja. Gleiche Antwort, die ich als ein Duplikat gekennzeichnet habe, obwohl –

+0

ich sehe. Es gibt keinen Platz für andere Lösung, denke ich. – wbars

Verwandte Themen