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

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

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

感谢您的帮助

最佳答案

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

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

关于java - 如何检查 BST 的结构是否对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43058595/

相关文章:

java - 保存文件变量以供以后使用?

java - 在这些行中查找特定模式的正确正则表达式是什么?

java - org.hibernate.id.enhanced.TableStructure - 无法读取 hi 值

scala - 在 Scala 中使用的标准二叉搜索树结构是什么?

matrix - 使用 awk 计算大文件的对称矩阵

Java - 打印分割字符串的几个不同部分

c++ - 清除二叉搜索树

c++ - 另一种二叉搜索树的节点公式

java - 检查数组是否对称

r - 从非对称矩阵(或数据帧)到具有 R 的对称方阵