简体   繁体   English

获取二叉树特定级别的所有节点

[英]Get all nodes of a specific level of a Binary Tree

I have a BinaryTree and I want to get all nodes of a specific level.我有一个BinaryTree ,我想获取特定级别的所有节点。 Order does not matter.顺序无所谓。 I want to try to do this with recursion .我想尝试用递归来做到这一点。 My method looks like this:我的方法如下所示:

public List<T> getNodesOnLevel(int i){
    int recursionTool = i
    //to do
    recursionTool-=1
    }

I tried to while(recursionTool.= 0){ method.... and then recursionTool -1} But I ended up getting all nodes until the wanted level.我试图 while(recursionTool.= 0){ method.... 然后 recursionTool -1} 但我最终得到了所有节点,直到想要的级别。 My Node looks like this:我的节点如下所示:

class Node<T>{
    T val;
    Node<T> left;
    Node<T> right;
    Node(T v){
        val = v;
        left = null;
        right = null;
    }

It is possible to implement this as a pure functional algorithm by concatenating the lists returned by recursive calls.通过连接递归调用返回的列表,可以将其实现为纯函数算法。 Unfortunately, that is rather inefficient in Java because all retrieved values are copied by list creation or concatenation once at each recursion level.不幸的是,这在 Java 中效率相当低,因为所有检索到的值都在每个递归级别通过列表创建或连接复制一次。

If you are willing to use mutation, here is a solution that avoids the copying (assuming that this is a Node<T> ):如果您愿意使用突变,这里有一个避免复制的解决方案(假设this是一个Node<T> ):

private void getNodesOnLevel(int level, List<T> list) {
    if (node == null) return;
    if (level == 0) {
        list.add(this.val);
    } else {
        this.left.getNodesOnLevel(level - 1, list);
        this.right.getNodesOnLevel(level - 1, list);
    }
}

The above method needs to be called with an empty (mutable) list as the 2nd argument, so we need another method:上面的方法需要用一个空(可变)列表作为第二个参数来调用,所以我们需要另一个方法:

public List<T> getNodesOnLevel(int level) {
    List<T> list = new ArrayList<>();
    this.getNodesOnLevel(level, list);
    return list;
}

(In complexity terms, the pure functional solution is O(LN) where L is the level and N is the number of nodes at that level. My solution is O(N) . Each value in the list will be copied twice on average, due to the way that ArrayList.append implements list resizing. The resizing could be avoided by creating the list with a capacity of 2 level .) (在复杂性方面,纯函数解决方案是O(LN)其中L是级别, N是该级别的节点数。我的解决方案是O(N) 。列表中的每个值平均被复制两次,由于ArrayList.append实现列表大小调整的方式。可以通过创建容量为 2 level的列表来避免调整大小。)

This may help you.这可能会对您有所帮助。 I had been used this method for print nodes but you can change it.我曾将这种方法用于打印节点,但您可以更改它。

public void printGivenLevel(TNode root, int level) {
    if (root == null)
        return;
    if (level == 1 && root.getValue() != null) {
   //  here,  add  root.getValue() to list
    } else if (level > 1) {
        printGivenLevel(root.getLeft(), level - 1);
        printGivenLevel(root.getRight(), level - 1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM