[算法]死磕二叉树专题算法
Posted 陈驰字新宇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[算法]死磕二叉树专题算法相关的知识,希望对你有一定的参考价值。
1. 二叉树遍历(递归和非递归)
构造二叉树:
class Node{ public String value; public Node left; public Node right; public Node(String value) { this.value = value; } }
递归版前序遍历:
public static void preOrder(Node head){ if(head != null){ System.out.print(head.value + " "); preOrder(head.left); preOrder(head.right); } }
递归版中序遍历:
public static void inOrder(Node head){ if(head != null){ inOrder(head.left); System.out.print(head.value + " "); inOrder(head.right); } }
递归版后序遍历:
public static void posOrder(Node head){ if(head != null){ posOrder(head.left); posOrder(head.right); System.out.print(head.value + " "); } }
非递归版前序遍历:
public static void preOrder(Node head){ if(head != null){ Stack<Node> stack = new Stack<>(); stack.push(head); while(!stack.isEmpty()){ Node pop = stack.pop(); System.out.print(pop.value + " "); if(pop.right != null) stack.push(pop.right); if(pop.left != null) stack.push(pop.left); } } }
非递归版中序遍历:
public static void inOrder(Node head){ if(head != null){ Stack<Node> stack = new Stack<>(); while(!stack.isEmpty() || head != null){ if(head != null){ stack.push(head); head = head.left; }else{ head = stack.pop(); System.out.print(head.value + " "); head = head.right; } } } }
非递归版后序遍历:
public static void postOrder(Node head){ if(head != null){ Stack<Node> stack1 = new Stack<>(); Stack<Node> stack2 = new Stack<>(); stack1.push(head); while(!stack1.isEmpty()){ Node pop = stack1.pop(); stack2.push(pop); if(pop.left != null){ stack1.push(pop.left); } if(pop.right != null){ stack1.push(pop.right); } } while(!stack2.isEmpty()){ System.out.print(stack2.pop().value + " "); } } }
这里用了两个栈,其实一个栈也能实现,这里这样做是因为可以和前序遍历对比着记,比较容易。
以上是关于[算法]死磕二叉树专题算法的主要内容,如果未能解决你的问题,请参考以下文章