JAVA 实现二叉树建立和先序,中序和后序遍历(递归与非递归)

假设通过二叉树对如下10个随机数进行排序
67,7,30,73,10,0,78,81,10,74
排序的第一个步骤是把数据插入到该二叉树中
插入基本逻辑是, 小、相同的放左边 大的放右边
1. 67 放在根节点
2. 7 比 67小,放在67的左节点
3. 30 比67 小,找到67的左节点7,30比7大,就放在7的右节点
4. 73 比67大, 放在67得右节点
5. 10 比 67小,找到67的左节点7,10比7大,找到7的右节点30,10比30小,放在30的左节点。
...
...

9. 10比67小,找到67的左节点7,10比7大,找到7的右节点30,10比30小,找到30的左节点10,10和10一样大,放在左边


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
/**
 * 二叉树
 * @author Administrator
 *
 */
public class Node {
	 // 左子节点
    public Node leftNode;
    // 右子节点
    public Node rightNode;
  
    // 值
    public Object value;
  
    // 插入 数据
    public void add(Object v) {
        // 如果当前节点没有值,就把数据放在当前节点上
        if (null == value)
            value = v;
  
        // 如果当前节点有值,就进行判断,新增的值与当前值的大小关系
        else {
            // 新增的值,比当前值小或者相同
             
            if ((Integer) v -((Integer)value) <= 0) {
                if (null == leftNode)
                leftNode = new Node();
                leftNode.add(v);
            }
            // 新增的值,比当前值大
            else {
                if (null == rightNode)
                rightNode = new Node();
                rightNode.add(v);
            }
  
        }
  
    }
    
   
    	
    //递归先序遍历  
    public static void preOrder(Node root){  
        if(root != null){  
            System.out.print(root.value+" ");  
            preOrder(root.leftNode);  
            preOrder(root.rightNode);  
        }  
    }  
    //非递归实现前序遍历  
    public static ArrayList preOrder1(Node root){  
        Stack<Node> stack = new Stack<Node>();  
        ArrayList alist = new ArrayList();  
        Node p = root;  
        while(p != null || !stack.empty()){  
            while(p != null){  
                alist.add(p.value);  
                stack.push(p);  
                p = p.leftNode;  
            }  
            if(!stack.empty()){  
                Node temp = stack.pop();  
                p = temp.rightNode;  
            }  
        }  
        return alist;  
    }  
    //中序遍历  
    public static void inOrder(Node root){  
        if(root != null){  
            inOrder(root.leftNode);  
            System.out.print(root.value+" ");  
            inOrder(root.rightNode);  
        }  
    } 
    //中序遍历所有的节点
    public List<Object> values(){
    	List<Object> values=new ArrayList<>();
    	
    	if(null!=leftNode) 
    		values.addAll(leftNode.values());
    		
    	values.add(value);
    	
    	if (null != rightNode)
            values.addAll(rightNode.values());
  
        return values;
    }
  //非递归实现中序遍历  
    public static ArrayList inOrder1(Node root){  
        ArrayList alist = new ArrayList();  
        Stack<Node> stack = new Stack<Node>();  
        Node p = root;  
        while(p != null || !stack.empty()){  
            while(p != null){  
                stack.push(p);  
                p = p.leftNode;  
            }  
            if(!stack.empty()){  
                Node temp = stack.pop();  
                alist.add(temp.value);  
                p = temp.rightNode;  
            }  
        }  
        return alist;  
    }  
    //后序遍历  
    public static void postOrder(Node root){  
        if(root != null){  
              
            postOrder(root.leftNode);  
            postOrder(root.rightNode); 
            System.out.print(root.value+" ");
        }  
    }
    
    //非递归实现二叉树的后序遍历  
    public static ArrayList postOrder1(Node root){  
        ArrayList alist = new ArrayList();  
        Stack<Node> stack = new Stack<Node>();  
        if(root == null)  
            return alist;  
        Node cur,pre = null;  
        stack.push(root);  
        while(!stack.empty()){  
            cur = stack.peek();  
            if((cur.leftNode == null && cur.rightNode == null) || (pre != null && (cur.leftNode == pre || cur.rightNode == pre))){  
                Node temp = stack.pop();  
                alist.add(temp.value);  
                pre = temp;  
            }  
            else{  
                if(cur.rightNode != null)  
                    stack.push(cur.rightNode);  
                if(cur.leftNode != null)  
                    stack.push(cur.leftNode);  
            }  
        }  
        return alist;  
    }  
    //非递归实现二叉树的层次遍历  
    public static void levelOrder(Node root) {  
        Queue<Node> queue = new LinkedList<Node>();  
        if(root == null)  
            return;  
        queue.offer(root);  
        while(!queue.isEmpty()){  
            Node temp  = queue.poll();  
            System.out.print(temp.value + " ");  
            if(temp.leftNode != null)  
                queue.offer(temp.leftNode);  
            if(temp.rightNode != null)  
                queue.offer(temp.rightNode);  
        }  
    }  
public static void main(String[] args) {
		int datas[]=new int[] {67,7,30,73,10,0,78,81,10,74};
		
		Node roots=new Node();
		for (int i : datas) {
			roots.add(i);
			
		}
		System.out.println("----------递归遍历--------");
		System.out.print("先序遍历:");
		roots.preOrder(roots);
		System.out.print("\n中序遍历:");
		roots.inOrder(roots);
		
		System.out.print("\t"+roots.values());//中序遍历节点
		
		System.out.print("\n后序遍历:");
		roots.postOrder(roots);
		
		System.out.println("\n---------非递归遍历--------");
		System.out.print("先序遍历:");
		System.out.println(preOrder1(roots));
		System.out.print("中序遍历:");
		System.out.println(inOrder1(roots));
		System.out.print("后序遍历:");
		System.out.println(postOrder1(roots));
		
		System.out.println("----------层次遍历--------");
		levelOrder(roots);
		
		  
        
	}
}


运行结果: 

----------递归遍历--------
先序遍历:67 7 0 30 10 10 73 78 74 81 
中序遍历:0 7 10 10 30 67 73 74 78 81 [0, 7, 10, 10, 30, 67, 73, 74, 78, 81]
后序遍历:0 10 10 30 7 74 81 78 73 67 
---------非递归遍历--------
先序遍历:[67, 7, 0, 30, 10, 10, 73, 78, 74, 81]
中序遍历:[0, 7, 10, 10, 30, 67, 73, 74, 78, 81]
后序遍历:[0, 10, 10, 30, 7, 74, 81, 78, 73, 67]
----------层次遍历--------
67 7 73 0 30 78 10 74 81 10 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
二叉树的遍历有三种方式:先序遍历、中序遍历后序遍历非递归算法实现二叉树的遍历需要借助栈来实现。 以先序遍历为例,具体实现步骤如下: 1. 创建一个栈,将根节点入栈。 2. 当栈不为空时,取出栈顶元素并访问它。 3. 如果该节点有右子树,则将右子树入栈。 4. 如果该节点有左子树,则将左子树入栈。 5. 重复步骤2-4,直到栈为空。 中序遍历后序遍历实现方式类似,只需要在访问节点的时机上稍作调整即可。 下面是先序遍历、中序遍历后序遍历非递归算法实现代码: ```c++ // 先序遍历 void preOrder(TreeNode* root) { if (root == nullptr) return; stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* node = s.top(); s.pop(); visit(node); if (node->right != nullptr) s.push(node->right); if (node->left != nullptr) s.push(node->left); } } // 中序遍历 void inOrder(TreeNode* root) { if (root == nullptr) return; stack<TreeNode*> s; TreeNode* node = root; while (node != nullptr || !s.empty()) { while (node != nullptr) { s.push(node); node = node->left; } node = s.top(); s.pop(); visit(node); node = node->right; } } // 后序遍历 void postOrder(TreeNode* root) { if (root == nullptr) return; stack<TreeNode*> s; TreeNode* node = root; TreeNode* lastVisited = nullptr; while (node != nullptr || !s.empty()) { while (node != nullptr) { s.push(node); node = node->left; } node = s.top(); if (node->right == nullptr || node->right == lastVisited) { visit(node); s.pop(); lastVisited = node; node = nullptr; } else { node = node->right; } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值