NodeTree类
public class NodeTree { private int num; private NodeTree left; private NodeTree right; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public NodeTree getLeft() { return left; } public void setLeft(NodeTree left) { this.left = left; } public NodeTree getRight() { return right; } public void setRight(NodeTree right) { this.right = right; } public NodeTree() { super(); } public NodeTree(int num) { super(); this.num = num; } public NodeTree(int num, NodeTree left, NodeTree right) { super(); this.num = num; this.left = left; this.right = right; } }
主要用迭代实现
public class Lianxi03 { private static int num=0; public static void main(String[] args) { NodeTree nodeTree=new NodeTree(0); method02(nodeTree,100); System.out.println(num); } public static void method02(NodeTree nodeTree,int num1){ if(nodeTree.getNum()==num1){ ++num; }else if (nodeTree.getNum()>num1) { }else if (nodeTree.getNum()<num1){ int temp=nodeTree.getNum(); // System.out.println(temp+"******"+num); NodeTree tempnode =nodeTree; nodeTree.setLeft(new NodeTree()); nodeTree=nodeTree.getLeft(); nodeTree.setNum(temp+1); method02(nodeTree,num1); tempnode.setRight(new NodeTree()); nodeTree=tempnode.getRight(); nodeTree.setNum(temp+2); method02(nodeTree,num1); } } }
还有个例子-----数的打印