二叉树的递归实现理解

BinaryTree 类的代码如下:

http://cslibrary.stanford.edu/110/BinaryTrees.html

重点理解:

1.理解递归方法,理解要又一个自变化的递归变量作参数;

2.privateNode insert(Node node,intdata)函数每次调用得到都是root根结点,而不是新加入的新结点.

3.此实现中内部静态类的使用:

1

  p.rivate Node root; 


 private static class Node
二者的顺序,先使用后定义,是由于Node作为静态类先加载。


2,node作为一个简单工厂模式中的产品,将抽象产品,具体产品,工厂角色3者合一之后,并作为内部类,就演变为静态类。

 

 private static class Node {

   Node left ; 

   Node right ; 

   int data; 

  

   Node(int newData) {

     left= null;

     right= null;

     data= newData;

   }
  static public Node getNode(int newData) { 
	return new Node(newData);
   }
 }


 

// BinaryTree.java

package study;

 

public class BinaryTree {

 // Root node pointer. Will be null for an empty tree.

 private Node root;

 

 private static class Node {

   Node left ;

   Node right ;

   int data;

 

   Node(int newData) {

     left= null;

     right= null;

     data= newData;

   }

 }

 

 /**

  Createsanempty binarytree -- a nullrootpointer.

 */

 public BinaryTree() {

   root= null;

 }

 

 /**

  Insertsthegiven data into thebinarytree.

  Usesarecursive helper.

 */

 public void insert(intdata) {

   root= insert(root , data);

 }

 

 

 /**

  Recursiveinsert-- given a nodepointer,recurdown and

  insertthegiven data into thetree.Returnsthenew

  nodepointer(thestandardwayto communicate

  achangedpointerbackto the caller).

 */

 private Node insert(Node node,intdata) {

   if(node==null) {

     node =new Node(data);

   }

   else{

     if(data <= node.data) {

       node.left = insert(node.left, data);

     }

     else{

       node.right = insert(node.right, data);

     }

   }

 

   return(node);// in any case, return the new pointer to the caller

 }

 

   

 publicvoid buildTree(int[] data){

    

    for (inti=0;i<data.length;i++){

        insert(data[i]);

     } 

 }

 

 publicvoid printTree() {

     printTree(root );

     System.out .println();

    }

 privatevoid printTree(Node node) {

    if (node ==null)return;

 

    // left, node itself, right

     printTree(node.left );

     System.out .print(node.data+ " );

     printTree(node.right );

    }

 

 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值