二叉树的建立及层次遍历及前中后序遍历递归与非递归的实现

38 篇文章 3 订阅
5 篇文章 1 订阅

二叉树的建立,遵循【左子树值 < 根结点值 < 右子树值】这一规律:

树的定义如下:

class BiTreeNode{
	int value;
	BiTreeNode left;
	BiTreeNode right;
}

树的建立如下:

public class BinaryTree{
	public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            int[] num = new int[n];
            for(int i=0; i<n; i++)
                num[i] = sc.nextInt();
			
			binarySort(num);
		}
	}
	
	BiTreeNode binarySort(int[] num) {
		if(num == null || num.length == 0)
			return null;

	   BiTreeNode root = intToNode(num[0]);
		for(int i=1; i<num.length; i++){
			if(searchBiTreeNode(root, num[i])) {
				BiTreeNode node = intToNode(num[i]);
				root = insertNode(root, node);
			}
		}

		return root;
	}
	
	boolean searchBiTreeNode(BiTreeNode root, int n){
		if(root != null){
			if(root.val == n)
				return false;
			if(root.val > n)
				searchBiTreeNode(root.left, n);
			if(root.val < n)
				searchBiTreeNode(root.right, n);
		}
		return true;
	}

	BiTreeNode intToNode(int n){
		BiTreeNode node = new BiTreeNode();
		node.val = n;
		node.left = null;
		node.right = null;
		return node;
	}

	BiTreeNode insertNode(BiTreeNode root, BiTreeNode node){
		if(root == null)
			root = node;
		else if(node.val < root.val)
		   root.left = insertNode(root.left, node);
		else
		   root.right = insertNode(root.right, node);

		return root;
	}	
}

二叉树的遍历是常见的,并且存在层次遍历、前中后序遍历,因此这里作一总结:实现二叉树的层次,以及先序、中序和后序遍历的递归方式和非递归方式。

 

二叉树的层次遍历:按“树根--->树叶”逐层访问结点。借助队列,访问当前结点时,将当前结点出险并将该结点的左右子结点入队

/*二叉树的层次遍历*/
void levelOrder(BiTreeNode root){
	if(root == null)
		return;
	
	Queue<BiTreeNode> queue = new LinkedList<>();
	queue.add(root);
	while(!queue.isEmpty()){
		root = queue.poll();
		System.out.print(root.value + " ");
		if(root.left != null)
			queue.offer(root.left);
		if(root.right != null)
			queue.offer(root.right);
	}
}

二叉树的先序遍历:按照“根--->左结点--->右结点”顺序访问结点。递归方法就调整打印时机,非递归方法借助栈,依次将根结点、右子结点、左结点入栈,然后栈首结点出栈并将该结点的左、右子树入结点

/*递归方法:先序遍历*/
void preOrder(BiTreeNode root){
	if(root == null)
		return;
	System.out.print(root.value + " ");
	if(root.left != null)
		preOrder(root.left);
	if(root.right != null)
		preOrder(root.right);
}

/*非递归方法:先序遍历*/
void preOrderUnRecur(BiTreeNode root){
	if(root != null){
		Stack<BiTreeNode> stack = new Stack<>();
		stack.add(root);
		while(!stack.isEmpty()){
			root = stack.pop();
			System.out.print(root.value + " ");
			if(root.right != null)
				stack.push(root.right);
			if(root.left != null)
				stack.push(root.left);
		}
	}		
}

二叉树的中序遍历:按照“左结点--->根--->右结点”顺序访问结点。递归方法就调整打印时机,非递归方法借助栈,先按左结点从根到叶结点入栈,直到最底层左结点,打印该结点,并转向右结点

/*递归方法:中序遍历*/
void inOrder(BiTreeNode root){
	if(root == null)
		return;
	if(root.left != null)
		inOrder(root.left);
	System.out.print(root.value + " ");
	if(root.right != null)
		inOrder(root.right);
}

/*非递归方法:中序遍历*/
void inOrderUnRecur(BiTreeNode root){
	if(root != null){
		Stack<BiTreeNode> 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.value + " ");
				root = root.right;
			}
		}
	}
}

二叉树的后序遍历:按照“左结点--->右结点--->根”顺序访问结点。递归方法就调整打印时机,非递归方法借助两个栈,按先序访问,另一个栈存储节点,最后统一打印

/*递归方法:后序遍历*/
void postOrder(BiTreeNode root){
	if(root == null)
		return;
	if(root.left != null)
		postOrder(root.left);
	if(root.right != null)
		postOrder(root.right);
	System.out.print(root.value + " ");
}

/*非递归方法:后序遍历*/
postOrderUnRecur(BiTreeNode root){
	Stack<BiTreeNode> stack = new Stack<>();
	Stack<BiTreeNode> print = new Stack<>();
	BiTreeNode node = root;
	while(node != null || !stack.isEmpty()){
		if(node != null){
			print.push(node);
			stack.push(node);
			node = node.right;
		}else{
			node = stack.pop();
			node = node.left;
		}
	}
	while(print.size() > 0)
		System.out.print(print.pop().value + " ");
}


 

Golang实现

package main

import (
	list2 "container/list"
	"fmt"
)

// 二叉树结构
type BTree struct {
	Val   int
	Left  *BTree
	Right *BTree
}

// 构建一棵二叉树
//      8
//    /   \
//   6     10
//  / \    / \
// 5   7  9   11
func newBTree() *BTree {
	node2_1 := &BTree{Val: 5}
	node2_2 := &BTree{Val: 7}
	node2_3 := &BTree{Val: 9}
	node2_4 := &BTree{Val: 11}
	node1_1 := &BTree{Val: 6, Left: node2_1, Right: node2_2}
	node1_2 := &BTree{Val: 10, Left: node2_3, Right: node2_4}
	root := &BTree{Val: 8, Left: node1_1, Right: node1_2}
	return root
}

// levelOrder 层次遍历
func levelOrder(root *BTree) {
	if root == nil {
		return
	}

	queue := newQueue()
	queue.push(root)
	for queue.len() > 0 {
		node := queue.pop().(*BTree)
		fmt.Printf("%d\t", node.Val)

		if node.Left != nil {
			queue.push(node.Left)
		}
		if node.Right != nil {
			queue.push(node.Right)
		}
	}
}

// 前序遍历[递归方式]
func preOrderRec(root *BTree) {
	if root == nil {
		return
	}

	fmt.Printf("%d\t", root.Val)
	if root.Left != nil {
		preOrderRec(root.Left)
	}
	if root.Right != nil {
		preOrderRec(root.Right)
	}
}

// 前序遍历[非递归方式]
func preOrderUnRec(root *BTree) {
	if root != nil {
		stack := newStack()
		stack.push(root)
		for stack.len() > 0 {
			node := stack.pop().(*BTree)
			fmt.Printf("%d\t", node.Val)

			if node.Right != nil {
				stack.push(node.Right)
			}
			if node.Left != nil {
				stack.push(node.Left)
			}
		}
	}
}

// 中序遍历[递归方式]
func inOrderRec(root *BTree) {
	if root == nil {
		return
	}

	if root.Left != nil {
		inOrderRec(root.Left)
	}
	fmt.Printf("%d\t", root.Val)
	if root.Right != nil {
		inOrderRec(root.Right)
	}
}

// 中序遍历[非递归方式]
func inOrderUnRec(root *BTree) {
	stack := newStack()
	node := root
	for stack.len() > 0 || node != nil {
		if node != nil {
			stack.push(node)
			node = node.Left
		} else {
			node = stack.pop().(*BTree)
			fmt.Printf("%d\t", node.Val)
			node = node.Right
		}
	}
}

// 后序遍历[递归方式]
func postOrderRec(root *BTree) {
	if root == nil {
		return
	}

	if root.Left != nil {
		postOrderRec(root.Left)
	}
	if root.Right != nil {
		postOrderRec(root.Right)
	}
	fmt.Printf("%d\t", root.Val)
}

// 后序遍历[非递归方式]
func postOrderUnRec(root *BTree) {
	store := newStack()
	show := newStack()
	node := root
	for store.len() > 0 || node != nil {
		if node != nil {
			store.push(node)
			show.push(node)
			node = node.Right
		} else {
			node = store.pop().(*BTree)
			node = node.Left
		}
	}
	for show.len() > 0{
		node = show.pop().(*BTree)
		fmt.Printf("%d\t", node.Val)
	}
}

///
func main() {
	root := newBTree()

	fmt.Printf("层次遍历:")
	levelOrder(root)

	fmt.Printf("\n前序遍历[递归方式]:  ")
	preOrderRec(root)

	fmt.Printf("\n前序遍历[非递归方式]:")
	preOrderUnRec(root)

	fmt.Printf("\n中序遍历[递归方式]:  ")
	inOrderRec(root)

	fmt.Printf("\n中序遍历[非递归方式]:")
	inOrderUnRec(root)

	fmt.Printf("\n后序遍历[递归方式]:  ")
	postOrderRec(root)

	fmt.Printf("\n后序遍历[非递归方式]:")
	postOrderUnRec(root)
}


/
// 自定义栈
type myStack struct {
	List *list2.List
}

func newStack() *myStack {
	stack := myStack{List: list2.New()}
	return &stack
}

func (stack *myStack) push(ele interface{}) {
	stack.List.PushBack(ele)
}

func (stack *myStack) pop() interface{} {
	if ele := stack.List.Back(); ele != nil {
		stack.List.Remove(ele)
		return ele.Value
	}
	return nil
}

func (stack *myStack) len() int {
	return stack.List.Len()
}


// 自定义队列
type myQueue struct {
	List *list2.List
}

func newQueue() *myQueue {
	queue := myQueue{List: list2.New()}
	return &queue
}

func (queue *myQueue) push(ele interface{}) {
	queue.List.PushBack(ele)
}

func (queue *myQueue) pop() interface{} {
	if ele := queue.List.Front(); ele != nil {
		queue.List.Remove(ele)
		return ele.Value
	}
	return nil
}

func (queue *myQueue) len() int {
	return queue.List.Len()
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值