package leetcode;
import sun.reflect.generics.tree.Tree;
import java.util.List;
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int x){
val = x;
}
}
public class SortBinaryTree {
public static TreeNode SortBinaryTree(TreeNode node,int i){
if(node == null){
node = new TreeNode(i);
return node;
}
else{
if(i <= node.val){
node.left = SortBinaryTree(node.left, i);
}else{
node.right = SortBinaryTree(node.right,i);
}
return node;
}
}
// 先序遍历
public static void preOrder(TreeNode root){
if(root != null){
System.out.print(root.val+"-");
preOrder(root.left);
preOrder(root.right);
}
}
// 递归中序遍历
public static void inOrder(TreeNode root){
if(root !=null){
inOrder(root.left);
System.out.print(root.val+"-");
inOrder(root.right);
}
}
// 递归后序遍历
public static void postOrder(TreeNode root){
if(root!=null){
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val+"-");
}
}
//非递归先序遍历
public static void preOrderfi(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode cur=root;
while (cur!=null || !stack.empty()){
if (cur!=null){
stack.push(cur);
System.out.print(cur.val+"-");
cur=cur.left;
}else{
cur=stack.pop();
cur=cur.right;
}
}
}
// 非递归中序遍历
public static void inOrderfi(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur!=null || !stack.empty()){
if(cur!=null){
stack.push(cur);
cur=cur.left;
}else {
cur = stack.pop();
System.out.print(cur.val+"-");
cur=cur.right;
}
}
}
//非递归后续遍历
public static void postOrderfi(TreeNode root){
System.out.println();
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode last = null; //访问过的节点
while (cur!=null || !stack.empty()){
if (cur!=null){
stack.push(cur);
cur=cur.left;
}else {
cur=stack.peek();
if (cur.right!=null && cur.right!=last){ //如果右子树为空或者是已经访问过了
cur = cur.right;
}else{
System.out.print(cur.val+"-");
cur=stack.pop();
last=cur;
cur=null;
}
}
}
}
public static void main(String[] args){
int a []= {3,1,2,5,0,7,9,8};
SortBinaryTree btb = new SortBinaryTree();
TreeNode root = new TreeNode(a[0]); //以3这个节点为根节点
for(int i = 1; i<a.length; i++){
btb.SortBinaryTree(root, a[i]);
}
System.out.print("先序遍历:");
preOrderfi(root);
System.out.print("中序遍历");
inOrderfi(root);
System.out.print("后序遍历");
postOrder(root);
postOrderfi(root);
}
}
结果:
先序遍历:3-1-0-2-5-7-9-8-中序遍历0-1-2-3-5-7-8-9-后序遍历0-2-1-8-9-7-5-3-
0-2-1-8-9-7-5-3-
process finished with exit code 0