写在开头:
非递归同样需要用到栈结构去实现类似递归的这样一个操作,递归写法只不过很多步骤都由系统栈替我们完成,本质其实一样。
【先序】
【Code】
//先序遍历 public static void xianxubianli(Node head) { if(head!=null) { Stack<Node> tool = new Stack<TreeProblem.Node>(); tool.add(head); //当工具栈不为空时 while(!tool.isEmpty()) { //取出栈顶元素进行打印 head = tool.pop(); System.out.print(head.value+" "); if(head.right!=null) tool.push(head.right); if(head.left!=null) tool.push(head.left); } } }
【中序】
//中序遍历 public static void zhongxubianli(Node head) { if(head!=null) { Stack<Node>p = new Stack<TreeProblem.Node>(); while(!p.isEmpty()||head!=null) { if(head!=null) { p.push(head); head=head.left; } else { head = p.pop(); System.out.print(head.value+" "); head = head.right; } } } }
【后序】
public static void houxubianli(Node head) { if(head!=null) { Stack<Node>p1 = new Stack<TreeProblem.Node>(); Stack<Node>p2 = new Stack<TreeProblem.Node>(); p1.push(head); while(!p1.isEmpty()) { head = p1.pop(); p2.push(head); if(head.left!=null) p1.push(head.left); if(head.right!=null) p1.push(head.right); } while(!p2.isEmpty()) { System.out.print(p2.pop().value+" "); } } }
原文:https://www.cnblogs.com/pionice/p/14374629.html