操作右节点较小,左节点较大

时间:2017-03-26 11:00:31

标签: c# binary-tree

如果右节点小于Head并且左节点比Head大,我需要编写返回true的操作。我试着检查它,但每次都返回false。

public static bool IsRightSmallANDLeftBig(BinNode<int> Head)
    {
        if (Head == null)
            return false; // no leaves and no parent.

        if (IsLeaf(Head))
            return false; // head is a leaf, so there is no parent.

        var right = Head.GetRight();
        var left = Head.GetLeft();

        if (left != null)
        {
            if (left.GetValue() < Head.GetValue())
                return true;
            else if (!IsRightSmallANDLeftBig(left))
                return false;
        }
        if (right != null)
        {
            if (right.GetValue() > Head.GetValue())
                return true;
            else if (!IsRightSmallANDLeftBig(right))
                return false;
        }

        return true;

    }

再次尝试但是当它到达叶子时它返回false:

public static bool IsRightSmallANDLeftBig(BinNode<int> Head)
    {
        if (Head == null)
            return false; // no leaves and no parent ~null~.

        var right = Head.GetRight();
        var left = Head.GetLeft();
        if (left == null && right == null)
            return false;
        if (left == null && right != null)
            return IsRightSmallANDLeftBig(right);
        if (left != null && right == null)
            return IsRightSmallANDLeftBig(left);
        if (left != null && right != null)
        {
            if (left.GetValue() > Head.GetValue() && right.GetValue() < Head.GetValue())
            {
                return IsRightSmallANDLeftBig(left) && IsRightSmallANDLeftBig(right);
            }
        }

            return false;

    }

0 个答案:

没有答案