Binary Trees question. Checking for similar shape

后端 未结 5 604
刺人心
刺人心 2021-01-06 06:49

Hi I\'m stuck doing this, not sure how to go about it.

If I have two binary trees, how would I check if the have the same shape? Data in the nodes doesn\'t matter, j

5条回答
  •  日久生厌
    2021-01-06 07:28

    You can easily do that with recursion. This following code works because two non-empty trees have the same shape if and only if their respective subtrees have the same shape.

    boolean equalTrees(Node lhs, Node rhs)
    {
        // Empty trees are equal
        if (lhs == null && rhs == null)
            return true;
    
        // Empty tree is not equal to a non-empty one
        if ((lhs == null && rhs != null)
            || (lhs != null && rhs == null))
            return false;
    
        // otherwise check recursively
        return equalTrees(lhs.left(), rhs.left())
            && equalTrees(lhs.right(), rhs.right())
    }
    

    To check two trees, pass their root nodes to the function above.

    equalTrees(tree1.root(), tree2.root())
    

提交回复
热议问题