【问题标题】:Insertion Binary Tree插入二叉树
【发布时间】:2019-08-26 03:39:45
【问题描述】:

您好,我正在阅读二叉树中的值插入,但我发现很难理解使用 Java 对树进行递归遍历。 代码如下:

// Java program to insert element in binary tree 
import java.util.LinkedList; 
import java.util.Queue; 
public class GFG { 

/* A binary tree node has key, pointer to  
left child and a pointer to right child */
static class Node { 
    int key; 
    Node left, right; 

    // constructor 
    Node(int key){ 
        this.key = key; 
        left = null; 
        right = null; 
    } 
} 
static Node root; 
static Node temp = root; 

/* Inorder traversal of a binary tree*/
static void inorder(Node temp) 
{ 
    if (temp == null) 
        return; 

    inorder(temp.left); 
    System.out.print(temp.key+" "); 
    inorder(temp.right); 
} 

/*function to insert element in binary tree */
static void insert(Node temp, int key) 
{ 
    Queue<Node> q = new LinkedList<Node>(); 
    q.add(temp); 

    // Do level order traversal until we find 
    // an empty place.  
    while (!q.isEmpty()) { 
        temp = q.peek(); 
        q.remove(); 

        if (temp.left == null) { 
            temp.left = new Node(key); 
            break; 
        } else
            q.add(temp.left); 

        if (temp.right == null) { 
            temp.right = new Node(key); 
            break; 
        } else
            q.add(temp.right); 
    } 
} 

// Driver code 
public static void main(String args[]) 
{ 
    root = new Node(10); 
    root.left = new Node(11); 
    root.left.left = new Node(7); 
    root.right = new Node(9); 
    root.right.left = new Node(15); 
    root.right.right = new Node(8); 

    System.out.print( "Inorder traversal before insertion:"); 
    inorder(root); 

    int key = 12; 
    insert(root, key); 

    System.out.print("\nInorder traversal after insertion:"); 
    inorder(root); 
} 
}

有人能解释一下这个 inorder() 方法是如何工作的吗?对我来说,它永远不应该终止,因为它会一次又一次地传递空值,并且 if 循环中的 return 语句只会循环出循环而不是整个方法。

【问题讨论】:

  • 你显然不懂递归,查一下。代码非常清晰,如果传递给inorder 的节点是null,它将不再向下进入树。
  • 在 youtube 或任何其他平台上寻找一棵树的中序遍历,你可以找到有详细解释的。

标签: java recursion data-structures binary-tree insertion


【解决方案1】:

inorder 被称为recursively

在任何给定的方法调用中,我们首先传入树的左节点,然后传入右节点。然后,这些调用将调用左节点或右节点的方法,但是 - 如果节点为空,它会提前返回。树不是无限的 - 所以在某一时刻节点的左右节点必须为空,此时该方法会提前返回并且不会继续。因此,递归在某些时候被安全地破坏了。

另外,if 不是循环 - 它是一个条件语句。在 if 中调用 return 会从整个方法返回,而不仅仅是退出 if 语句。你肯定把它和break混淆了。

【讨论】:

  • 谢谢我调试了这段代码,但是在 temp = null 并且递归被破坏之后......在下一个 print 语句中 temp.key 如何打印值,因为 temp 为 null?
  • 我猜是因为它为左右节点调用inorder。因此,如果左节点为空,则父调用仍会继续它的 inorder 调用,因为父节点不为空 - 因此正在调用 print,并且为右节点再次执行该方法。
  • 谢谢,我不明白这个父调用部分我想我必须先查看一些递归文档。
  • 如果它在 temp = null 之后终止,那么为什么 inorder 调用仍然继续......这有什么原因吗?
  • inorder 第一次从根节点被调用时,它会检查根节点是否为空——它不是,所以它继续它的调用。然后它继续为左节点调用inorder,它提前返回,所以那里什么都没有发生-该方法基本上是noop 然后继续打印密钥,这确实发生了,因为我们仍在根的调用中inorder。之后它继续调用inorder 以获得正确的节点,这可能仍然是一个noop,但这没关系。打印被称为任何一种方式。想象一下它有点像 Inception :D
猜你喜欢
  • 2015-02-13
  • 1970-01-01
  • 2022-01-14
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 2015-05-16
相关资源
最近更新 更多