【问题标题】:Check that sum of left and right children values equal value of the parent in Binary Trees?检查二叉树中左右子项的总和是否等于父项的值?
【发布时间】:2016-07-26 05:43:30
【问题描述】:

我正在写一个二叉树作业问题的方法。

目标:
给定一棵二叉树,检查树是否满足对于每个节点,其左右子节点的值之和等于节点值的属性。如果一个节点只有一个孩子,那么该节点应该与那个孩子具有相同的值。叶节点自动满足该属性。

我收到一条错误消息,指出我的代码在所有情况下都不正确。例如,如果我有一棵树

15
/ \
5 10

当它应该为真时,我返回假。

到目前为止,这是我的方法,我做错了什么?

boolean BTchecksum(BinNode root) {
    if (root == null || root.left() == null && root.right() == null) {return true;}

    BinNode leftNode = root.left();
    BinNode rightNode = root.right();

    int sum = (int)(leftNode.element()) + (int)(leftNode.element());
    int value = (int)(root.element());

    return (sum == value) && BTchecksum(root.left()) && BTchecksum(root.right());

}

【问题讨论】:

    标签: java recursion methods binary-tree


    【解决方案1】:

    你把 sum 写成: leftNode.element()) + (int)(leftNode.element)));

    应该是这样的: leftNode.element()) + (int)(rightNode.element)));

    【讨论】:

    • 发生在我们最好的人身上!
    【解决方案2】:

    现在,您可能会遇到空指针异常,因为您正在引用可能为空的子项。这可能不是最有效的解决方案,但它可以处理所有情况。

    public boolean BTchecksum(BinNode root) {
        if (root == null || root.right()==null && root.left()==null) {
            return true;
        }
        if (root.right() == null) {
            return (root.left().value() == root.value()) 
                && BTchecksum(root.left());
        } else if (root.left() == null) {
            return (root.right().value() == root.value()) 
                && BTchecksum(root.right());
        } else {
            return (root.value() == root.left().value() + root.right().value()) 
                && BTchecksum(root.left()) && BTchecksum(root.right());
    }
    

    【讨论】:

      【解决方案3】:

      修订版(无 NullPinterException)

      public boolean BTchecksum(BinNode root)
      {   
          if (root == null || root.left() == null && root.right() == null) {return true;}
      
          int sum = 0;
          if (root.left() != null){sum = sum + root.left().value();}
          if (root.right() != null){sum = sum + root.right().value();}
      
          return (sum == root.value()) && BTchecksum(root.left()) && BTchecksum(root.right());
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-02
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 2021-12-26
        • 2019-11-21
        • 1970-01-01
        相关资源
        最近更新 更多