返回二叉树级别的方法

时间:2015-03-29 20:29:36

标签: java binary-tree

以下内容来自求职面试:

  

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

我可以在这里得到你的帮助吗?

感谢。

1 个答案:

答案 0 :(得分:2)

我想你有一个名为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;
}

是否清楚?