二叉树的创建和非递归遍历
import org.junit.Test;
import java.util.Stack;
public class createTree {
Node root = null;
/**
* 创建
* @param data
*/
public void add1(int data){
Node newNode = new Node(data);
if(root == null){
root = newNode;
return ;
}
Node current = root;
Node parent;
while(true){
parent = current;
if(data<current.data){
current = current.left;
if(current == null){
parent.left = newNode;
return ;
}
}else{
current = current.right;
if(current == null){
parent.right = newNode;
return;
}
}
}
}
/**
* 非递归先序遍历
*/
public void preOrder(Node root){
if(root != null){
Stack<Node> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()){
root = stack.pop();
System.out.print(root.data+" ");
if(root.right!=null){
stack.add(root.right);
}
if(root.left != null){
stack.add(root.left);
}
}
}
System.out.println();
}
/**
* 非递归中序遍历
* @param root
*/
public void inOrder(Node root){
if(root != null){
Stack<Node> stack = new Stack<>();
while(!stack.isEmpty() || root!=null){
if(root != null){
stack.push(root);
root = root.left;
}else{
root = stack.pop();
System.out.print(root.data+" ");
root = root.right;
}
}
}
System.out.println();
}
/**
* 非递归后续遍历
* @param root
*/
public void posOrder(Node root){
if(root != null){
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(root);
while(!s1.isEmpty()){
root = s1.pop();
s2.push(root);
if(root.left != null){
s1.push(root.left);
}
if(root.right != null){
s1.push(root.right);
}
}
while(!s2.isEmpty()){
System.out.print(s2.pop().data+" ");
}
}
System.out.println();
}
//最普通的创建方式,测试时比较实用
public Node add(){
Node no1 = new Node(1);
Node no2 = new Node(2);
Node no3 = new Node(3);
Node no4 = new Node(4);
Node no5 = new Node(5);
Node no6 = new Node(6);
Node no7 = new Node(7);
no1.left = no2;
no1.right = no3;
no2.left = no4;
no2.right = no5;
no3.left = no6;
no3.right = no7;
return no1;
}
@Test
public void test(){
Node temp1 = add();
Node temp2 = add();
Node temp3 = add();
preOrder(temp1);
inOrder(temp2);
posOrder(temp3);
}
}
那位大哥有按层创建二叉树的方式和思想,能不能分享一下,在此万分感谢