📜  检查BST的每个内部节点是否恰好有一个子节点

📅  最后修改于: 2021-05-25 00:24:42             🧑  作者: Mango

给定BST的遍历顺序,请检查每个非叶节点是否只有一个子节点。假定BST包含唯一的条目。
例子

Input: pre[] = {20, 10, 11, 13, 12}
Output: Yes
The give array represents following BST. In the following BST, every internal
node has exactly 1 child. Therefor, the output is true.
        20
       /
      10
       \
        11
          \
           13
           /
         12

在预遍历中,每个节点的后代(或预序后继)出现在该节点之后。在上面的示例中,20是预排序中的第一个节点,所有20的后代都出现在其后。 20的所有后代都小于它。对于10,所有后代都大于它。通常,我们可以说,如果在BST中所有内部节点只有一个孩子,那么每个节点的所有后代都将小于或大于该节点。原因很简单,因为树是BST,并且每个节点只有一个孩子,所以节点的所有后代将在左侧或右侧,这意味着所有后代将变小或变大。
方法1(天真)
该方法仅遵循上述想法,即右侧的所有值都较小或较大。使用两个循环,外部循环从最左边的元素开始一个接一个地选择一个元素。内部循环检查拾取的元素右侧的所有元素是否较小或较大。该方法的时间复杂度将为O(n ^ 2)。
方法2
由于节点的所有后代必须大于或小于该节点。我们可以对循环中的每个节点执行以下操作。
1.查找节点的下一个预购后继者(或后代)。
2.查找节点的最后一个预后继者(pre []中的最后一个元素)。
3.如果两个后继节点均小于当前节点,或者两个后继节点均大于当前节点,则继续。否则,返回false。

C
#include 
 
bool hasOnlyOneChild(int pre[], int size)
{
    int nextDiff, lastDiff;
 
    for (int i=0; i


Java
// Check if each internal node of BST has only one child
 
class BinaryTree {
 
    boolean hasOnlyOneChild(int pre[], int size) {
        int nextDiff, lastDiff;
 
        for (int i = 0; i < size - 1; i++) {
            nextDiff = pre[i] - pre[i + 1];
            lastDiff = pre[i] - pre[size - 1];
            if (nextDiff * lastDiff < 0) {
                return false;
            };
        }
        return true;
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        int pre[] = new int[]{8, 3, 5, 7, 6};
        int size = pre.length;
        if (tree.hasOnlyOneChild(pre, size) == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3
# Check if each internal
# node of BST has only one child
 
def hasOnlyOneChild (pre, size):
    nextDiff=0; lastDiff=0
  
    for i in range(size-1):
        nextDiff = pre[i] - pre[i+1]
        lastDiff = pre[i] - pre[size-1]
        if nextDiff*lastDiff < 0:
            return False
    return True
  
# driver program to
# test above function
if __name__ == "__main__":
 
    pre = [8, 3, 5, 7, 6]
    size= len(pre)
 
    if (hasOnlyOneChild(pre,size) == True):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Harshit Saini


C#
// Check if each internal node of BST has only one child
using System;
public class BinaryTree
{
 
  bool hasOnlyOneChild(int[] pre, int size)
  {
    int nextDiff, lastDiff;
    for (int i = 0; i < size - 1; i++)
    {
      nextDiff = pre[i] - pre[i + 1];
      lastDiff = pre[i] - pre[size - 1];
      if (nextDiff * lastDiff < 0)
      {
        return false;
      };
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    int []pre = new int[]{8, 3, 5, 7, 6};
    int size = pre.Length;
    if (tree.hasOnlyOneChild(pre, size) == true)
    {
      Console.WriteLine("Yes");
    }
    else
    {
      Console.WriteLine("No");
    }
  }
}
 
// This code is contributed by aashish1995


C
#include 
 
int hasOnlyOneChild(int pre[], int size)
{
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size-1] > pre[size-2])
    {
        max = pre[size-1];
        min = pre[size-2]):
    else
    {
        max = pre[size-2];
        min = pre[size-1];
    }
 
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i=size-3; i>=0; i--)
    {
        if (pre[i] < min)
            min = pre[i];
        else if (pre[i] > max)
            max = pre[i];
        else
            return false;
    }
    return true;
}
 
// Driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre,size))
        printf("Yes");
    else
        printf("No");
    return 0;
}


Java
// Check if each internal node of BST has only one child
 
class BinaryTree {
 
    boolean hasOnlyOneChild(int pre[], int size) {
        // Initialize min and max using last two elements
        int min, max;
        if (pre[size - 1] > pre[size - 2]) {
            max = pre[size - 1];
            min = pre[size - 2];
        } else {
            max = pre[size - 2];
            min = pre[size - 1];
        }
 
        // Every element must be either smaller than min or
        // greater than max
        for (int i = size - 3; i >= 0; i--) {
            if (pre[i] < min) {
                min = pre[i];
            } else if (pre[i] > max) {
                max = pre[i];
            } else {
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        int pre[] = new int[]{8, 3, 5, 7, 6};
        int size = pre.length;
        if (tree.hasOnlyOneChild(pre, size) == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal


Python3
# Check if each internal
# node of BST has only one child
# approach 2
 
def hasOnlyOneChild(pre,size):
 
    # Initialize min and max
    # using last two elements
    min=0; max=0
 
    if pre[size-1] > pre[size-2] :
        max = pre[size-1]
        min = pre[size-2]
    else :
        max = pre[size-2]
        min = pre[size-1]
  
    # Every element must be
    # either smaller than min or
    # greater than max
    for i in range(size-3, 0, -1):
        if pre[i] < min:
            min = pre[i]
        elif pre[i] > max:
            max = pre[i]
        else:
            return False
    return True
  
# Driver program to
# test above function
if __name__ == "__main__":
 
    pre = [8, 3, 5, 7, 6]
 
    size = len(pre)
    if (hasOnlyOneChild(pre, size)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Harshit Saini


C#
// Check if each internal node of BST has only one child
using System;
public class BinaryTree
{
 
  bool hasOnlyOneChild(int []pre, int size)
  {
 
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size - 1] > pre[size - 2]) {
      max = pre[size - 1];
      min = pre[size - 2];
    } else {
      max = pre[size - 2];
      min = pre[size - 1];
    }
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i = size - 3; i >= 0; i--) {
      if (pre[i] < min) {
        min = pre[i];
      } else if (pre[i] > max) {
        max = pre[i];
      } else {
        return false;
      }
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    int []pre = new int[]{8, 3, 5, 7, 6};
    int size = pre.Length;
    if (tree.hasOnlyOneChild(pre, size) == true)
    {
      Console.WriteLine("Yes");
    }
    else
    {
      Console.WriteLine("No");
    }
  }
}
 
// This code is contributed by aashish1995


输出:

Yes 

方法3
1.扫描预购的最后两个节点,并将它们标记为“最小”和“最大”。
2.扫描预定阵列中的每个节点。每个节点必须小于最小节点或大于最大节点。相应地更新最小和最大。

C

#include 
 
int hasOnlyOneChild(int pre[], int size)
{
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size-1] > pre[size-2])
    {
        max = pre[size-1];
        min = pre[size-2]):
    else
    {
        max = pre[size-2];
        min = pre[size-1];
    }
 
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i=size-3; i>=0; i--)
    {
        if (pre[i] < min)
            min = pre[i];
        else if (pre[i] > max)
            max = pre[i];
        else
            return false;
    }
    return true;
}
 
// Driver program to test above function
int main()
{
    int pre[] = {8, 3, 5, 7, 6};
    int size = sizeof(pre)/sizeof(pre[0]);
    if (hasOnlyOneChild(pre,size))
        printf("Yes");
    else
        printf("No");
    return 0;
}

Java

// Check if each internal node of BST has only one child
 
class BinaryTree {
 
    boolean hasOnlyOneChild(int pre[], int size) {
        // Initialize min and max using last two elements
        int min, max;
        if (pre[size - 1] > pre[size - 2]) {
            max = pre[size - 1];
            min = pre[size - 2];
        } else {
            max = pre[size - 2];
            min = pre[size - 1];
        }
 
        // Every element must be either smaller than min or
        // greater than max
        for (int i = size - 3; i >= 0; i--) {
            if (pre[i] < min) {
                min = pre[i];
            } else if (pre[i] > max) {
                max = pre[i];
            } else {
                return false;
            }
        }
        return true;
    }
 
    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();
        int pre[] = new int[]{8, 3, 5, 7, 6};
        int size = pre.length;
        if (tree.hasOnlyOneChild(pre, size) == true) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }
}
 
// This code has been contributed by Mayank Jaiswal

Python3

# Check if each internal
# node of BST has only one child
# approach 2
 
def hasOnlyOneChild(pre,size):
 
    # Initialize min and max
    # using last two elements
    min=0; max=0
 
    if pre[size-1] > pre[size-2] :
        max = pre[size-1]
        min = pre[size-2]
    else :
        max = pre[size-2]
        min = pre[size-1]
  
    # Every element must be
    # either smaller than min or
    # greater than max
    for i in range(size-3, 0, -1):
        if pre[i] < min:
            min = pre[i]
        elif pre[i] > max:
            max = pre[i]
        else:
            return False
    return True
  
# Driver program to
# test above function
if __name__ == "__main__":
 
    pre = [8, 3, 5, 7, 6]
 
    size = len(pre)
    if (hasOnlyOneChild(pre, size)):
        print("Yes")
    else:
        print("No")
 
# This code is contributed by
# Harshit Saini

C#

// Check if each internal node of BST has only one child
using System;
public class BinaryTree
{
 
  bool hasOnlyOneChild(int []pre, int size)
  {
 
    // Initialize min and max using last two elements
    int min, max;
    if (pre[size - 1] > pre[size - 2]) {
      max = pre[size - 1];
      min = pre[size - 2];
    } else {
      max = pre[size - 2];
      min = pre[size - 1];
    }
 
    // Every element must be either smaller than min or
    // greater than max
    for (int i = size - 3; i >= 0; i--) {
      if (pre[i] < min) {
        min = pre[i];
      } else if (pre[i] > max) {
        max = pre[i];
      } else {
        return false;
      }
    }
    return true;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    BinaryTree tree = new BinaryTree();
    int []pre = new int[]{8, 3, 5, 7, 6};
    int size = pre.Length;
    if (tree.hasOnlyOneChild(pre, size) == true)
    {
      Console.WriteLine("Yes");
    }
    else
    {
      Console.WriteLine("No");
    }
  }
}
 
// This code is contributed by aashish1995

输出:

Yes