Java 方法,该方法返回二叉树级别

Java 方法,该方法返回二叉树级别,java,binary-tree,Java,Binary Tree,以下内容摘自一次工作面试: 对于二叉树,编写一个函数,以返回 其中节点的总和最小 你能帮我吗 谢谢。我想您有一个名为Node的数据结构,其值可以使用Node.value和Node.left、Node.right来访问分支。 像这样的 `Node{int value, Node left, Node right}` 我还没有测试过这段代码,所以它可能不起作用,但我认为这个想法是好的。 我使用一个arraylist,在其中,每次迭代,我都会放置一个级别的节点 int getIndexOfMinim

以下内容摘自一次工作面试:

对于二叉树,编写一个函数,以返回 其中节点的总和最小

你能帮我吗


谢谢。

我想您有一个名为Node的数据结构,其值可以使用
Node.value
Node.left、Node.right
来访问分支。 像这样的

`Node{int value, Node left, Node right}`
我还没有测试过这段代码,所以它可能不起作用,但我认为这个想法是好的。 我使用一个arraylist,在其中,每次迭代,我都会放置一个级别的节点

int getIndexOfMinimalLevel(Node root){
  ArrayList<Node> todo = new Arraylist(); //Nodes of the current level
  ArrayList<Node> done = new ArrayList(); //Nodes processed

  int minLevel = 0;  //index of the current minimal level
  int currLevel = 0; //index of the current level
  int minLevelSum = root.value; //sum of values of the nodes of the minimal level
  todo.add(root); //current level contains only the root node

  while(todo.size()>0){ //while there are nodes of this level
    int currLevelSum = 0; //sum of the values of nodes of this level
    for(int i=0; i<todo.size(); i++){ //for each node in this level
      currLevelsum+=todo.get(0).value; //add his value to sum
      done.add(todo.remove(0)); //remove it and put it in the done list
    }
    if(currLevelSum < minLevelSum){ //if this level has the lowest sum since now
      minLevel = currLevel; //the minimal sum level index is the index of this level
      minLevelSum = currLevelSum //the lowest sum is the sum of the values of the nodes of this level
    }
    Node tmp;
    for(int i=0; i<done.size(); i++){ //for every node processed
      tmp=done.get(0);     
      if(tmp.left!=null){     //if it has a left child
        todo.add(root.left);  //add it to the todo list
      }
      if(root.right!=null){   //if it has a right child
        todo.add(root.right); //add it to the todo list
      }
      done.remove(0);         //remove it from the done list
    }
    currLevel++;
  }
  return minLevel;
}
int getIndexOfMinimalLevel(节点根){
ArrayList todo=新建ArrayList();//当前级别的节点
ArrayList done=新建ArrayList();//已处理节点
int minLevel=0;//当前最小级别的索引
int currLevel=0;//当前级别的索引
int minLevelSum=root.value;//最小级别节点的值之和
todo.add(root);//当前级别仅包含根节点
while(todo.size()>0){//while存在此级别的节点
int currLevelSum=0;//此级别节点的值之和

对于(int i=0;i二叉树是如何实现的?@MisterDev您将树的根作为方法的输入值…我正在尝试编写一个函数。是否有使用TreeSet或TreeSet的较短解决方案?谢谢!我已经看过了,但我不熟悉TreeSet或TreeSet,对不起