首页 > 解决方案 > 一旦我到达节点 e,方法中会发生什么?因为在节点 e 上,n 是对空值的引用。从 if 返回后程序会去哪里

问题描述

             a
            / \
          b    g
         / \
        c   d
       /
      e
       \
        f    



public static Node createData() {   //this is the nodes which make up the tree structure
    
Node a = new Node( "a");
Node b = new Node( "b");
Node c = new Node( "c");
Node d = new Node( "d");
Node e = new Node( "e");
Node f = new Node( "f");
Node g = new Node( "g");           

a.left = b;  //this block of code connects the nodes to the specific tree should look
a.right = g;
b.left = c;
b.right = d;
c.left = e;
e.right = f;


public static void preOrderTraversal(Node n) { // method recursively traverses through using preOrder

if(n == null)

return;

System.out.println(n.value + " "); 

preOrderTraversal(n.left);

preOrderTraversal(n.right); 

}

//我了解a、b、c和e是如何输出的。但是,一旦我们到达节点 e,n 就是对空值的引用。那么当我们进入一个空值的方法时,在我们进入if语句之后,我们究竟“返回”到哪里呢?就像此时程序跳转到哪里/现在正在查看哪一行?一旦 n 是对空值的引用,我就很难理解该方法是如何工作的。顺便说一下,preOrder Traversal 有以下 3 个步骤:访问节点、向左遍历、向右遍历。然后递归地重复

标签: methodsbinary-treenodestree-traversalpreorder

解决方案


推荐阅读