刷题_day3_vv

package com.vv;


import java.util.Stack;


/**
 * 题目:非递归实现二叉树的遍历
 *  思路:非递归遍历需要借助一个自己申请的数据结构来代替递归遍历中函数栈的作用
 *  
 * @author vv 2016.4.7
 *
 */
public class day3 {


// 非递归的方法先序遍历
public void preOrderUnrecur(Node head) {
if (head != null) {
Stack stack = new Stack();
// 头结点先入栈
stack.push(head);
while (!stack.empty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null)
stack.push(head.right);
if (head.right != null)
stack.push(head.left);
}
}
}


// 非递归实现中序遍历
public void inOrderUnrecur(Node head) {
if (head != null) {
Stack stack = new Stack();
while (!stack.empty() && head != null) {


if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.println(head.value + " ");


head = head.right;
}
}
}
}
}


class Node {// 二叉树节点


public int value;
public Node left;
public Node right;


public Node(int data) {
this.value = data;
}
}

你可能感兴趣的:(LeetCode)