import java.util.Stack; public class test14 { public static class Node{ public int value; public Node left; public Node right; public Node(int v){ value = v; } } //先序、中序、后序遍历都可以在递归序的基础加工出来 //第一次到达一个节点就打印为先序、第二次为中序、第三次为后序 public static void f(Node head){ if(head ==null){ return; } f(head.left); f(head.right); } //递归实现 //先序遍历 public static void pre1(Node head){ if (head == null){ return; } System.out.println(head.value); pre1(head.left); pre1(head.right); } //中序遍历 public static void in1(Node head){ if (head == null){ return; } in1(head.left); System.out.println(head.value); in1(head.right); } //后序遍历 public static void pos1(Node head){ if (head == null){ return; } pos1(head.left); pos1(head.right); System.out.println(head.value); } //非递归实现 //先序 public static void pre2(Node head){ //弹出就打印 //如果有右节点就压入右节点 //如果有左节点就压入左节点 //这样就保证了先出来左后出来右 if(head != null) { Stack<Node> stack = new Stack<Node>(); stack.add(head); while (!stack.isEmpty()) { head = stack.pop(); System.out.println(head.value + " "); if (head.right != null) { stack.push(head.right); } if (head.left != null) { stack.push(head.left); } } } System.out.println(); } //后序,两个栈实现 public static void pos2(Node head){ if(head != null){ Stack<Node> s1 = new Stack<Node>(); Stack<Node> s2 = new Stack<Node>(); s1.push(head); while (!s1.isEmpty()){ head = s1.pop(); s2.push(head); if(head.left != null){ s1.push(head.left); } if(head.right != null){ s1.push(head.right); } } while (!s2.isEmpty()){ System.out.println(s2.pop().value + " "); } } System.out.println(); } //中序 public static void in2(Node head){ if(head != null){ Stack<Node> stack = new Stack<Node>(); while (!stack.isEmpty() || head != null){ if(head != null){ stack.push(head); head = head.left; }else{ head = stack.pop(); System.out.println(head.value + " "); head = head.right; } } } System.out.println(); } //后序,一个栈实现 public static void pos3(Node h){ if(h != null){ Stack<Node> stack = new Stack<Node>(); stack.push(h); Node c = null; while (!stack.isEmpty()){ c = stack.peek(); if(c.left != null && h != c.left && h != c.right){ stack.push(c.left); }else if(c.left != null && h != c.right){ stack.push(c.right); }else{ System.out.println(stack.pop().value + " "); h = c; } } } } }
二叉树(先序中序和后序的实现)
最新推荐文章于 2024-08-12 16:47:32 发布