计算二叉树中所有节点的节点深度

时间:2020-09-15 19:30:03

标签: java algorithm recursion binary-tree

我正在尝试解决Node Depths question from Algoexpert。该问题要求您计算给定二叉树中所有节点的深度之和。例如,给定这棵树-

          1
       /     \
      2       3
    /   \   /   \
   4     5 6     7
 /   \
8     9

总和应为16。

我为此写了一个递归解决方案,我认为这是正确的,但有趣的是,只有第一个测试通过了,而其余的测试用例却失败了。这是我的解决方案-

import java.util.*;

class Program {

  // static variable to hold the final sum
  private static int finalSum = 0;

  public static int nodeDepths(BinaryTree root) {
        // Write your code here.
        int runningSum = 0;
        depthHelper(root.left, runningSum);
        depthHelper(root.right, runningSum);
        return finalSum;
  }
    
    private static void depthHelper(BinaryTree node, int runningSum) {
        if(node == null) return;
        runningSum++;
        finalSum += runningSum;
        depthHelper(node.left, runningSum); 
        depthHelper(node.right, runningSum);
    }

  static class BinaryTree {
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value) {
      this.value = value;
      left = null;
      right = null;
    }
  }
}

算法本身非常简单。

有一个runningSum变量(初始化为-1以说明根),每次访问新节点(即从其父节点向下一级)时,我都会向其中添加1。并且,在每次递归调用时,将此runningSum变量的值添加到finalSum变量中。

例如,在节点2,runningSum1,并将其添加到finalSum的{​​{1}}中。现在0变为finalSum。节点1相同,之后3变为finalSum。在节点2处,4变成runningSum2变成finalSum

第一个测试用例通过,并且我收到此消息-

enter image description here

但是,随后的所有情况都失败了。我认为可能会发生什么-之前测试用例执行的输出未清除,而是以某种方式添加到当前测试用例执行的结果中。

这就是为什么我认为这可能是原因-

4

注意如何清除先前执行的结果并将其添加到后续执行的“我们的代码输出”中。例如,在第二个测试用例中,“您的代码输出”结果显示 1. Test case 2 - our code output - 0, your code output - 16 2. Test case 3 - our code output - 1, your code output - 17 3. Test case 4 - our code output - 2, your code output - 19 4. Test case 5 - our code output - 4, your code output - 23 5. Test case 6 - our code output - 21, your code output - 44 6. Test case 7 - our code output - 42, your code output - 86 实际上是第一个测试用例的结果。

这是由于在代码中使用了全局16变量吗?但是我在Leetcode上多次使用了相同的方法,在那儿效果很好。

还是我的算法中存在其他错误?

PS-我知道在这里不喜欢使用屏幕截图,但是有可能这是特定于平台的问题,所以我不得不使用它。

2 个答案:

答案 0 :(得分:3)

在我看来,这种行为并不是错误。这是由于使所有内容都是静态的。有很多避免这种问题的可能性。其中两个解释如下:

使用静态方法但具有无状态的类:

    import React, {Component} from 'react';
    import Product from "./Product";
    import Title from './Title';
    import {ProductConsumer} from '../context';

    export default class ProductList extends Component{
    render() {               
        return(
        <React.Fragment>
        <div className="py-5">
        <div className="container">
        <Title name="our" title="products"/>

       <div className="row"> 
      <ProductConsumer>
     {value=>{
      return value.products.map( product =>{           #here is where the error is.
        return <Product key={product.id} product={product}/>;
      });
      }}              
    </ProductConsumer>
        </div>
        </div>
    </div>
        </React.Fragment>
       // <Product/>
    );
   }      
   }   

创建一个对象(如果您不只是对该对象执行一项操作,它将变得更加有用):

public static int nodeDepths(BinaryTree root) {
    // Write your code here.
    return depthHelper(root.left, 1) + depthHelper(root.right, 1);
}

private static int depthHelper(BinaryTree node, int sum) {
    if (node == null) return 0;
    return sum + depthHelper(node.left, sum + 1) + depthHelper(node.right, sum + 1);
}

两个实现都是线程安全的。

答案 1 :(得分:1)

好像他们的测试平台使用您的类的一个对象运行测试。因此,您应该在finalSum方法的末尾清除nodeDepths()

public static int nodeDepths(BinaryTree root) {
    // Write your code here.
    int runningSum = 0;
    depthHelper(root.left, runningSum);
    depthHelper(root.right, runningSum);
    int temp=finalSum;  
    finalsum=0; 
    return temp;
}
相关问题