注意二叉树节点的定义如下:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
递归实现:
// 用递归的方法进行先序遍历
public void qinaxuDigui(TreeNode treeNode) {
qianxuNumList.add(treeNode.val);
if (treeNode.left != null) {
qinaxuDigui(treeNode.left);
}
if (treeNode.right != null) {
qinaxuDigui(treeNode.right);
}
}
// 用递归的方法进行中序遍历
public void zhongxuDigui(TreeNode treeNode) {
if (treeNode.left != null) {
zhongxuDigui(treeNode.left);
}
zhongxuNumList.add(treeNode.val);
if (treeNode.right != null) {
zhongxuDigui(treeNode.right);
}
}
// 用递归的方法进行后序遍历
public void houxuDigui(TreeNode treeNode) {
if (treeNode.left != null) {
houxuDigui(treeNode.left);
}
if (treeNode.right != null) {
houxuDigui(treeNode.right);
}
houxuNumList.add(treeNode.val);
}
非递归实现:
// 用非递归的方法进行先序遍历
public void qinaxuFeiDigui(TreeNode treeNode) {
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
qianxuNumList.add(treeNode.val);
stack.push(treeNode);
treeNode = treeNode.left;
}
if(!stack.isEmpty()){
treeNode = stack.pop();
treeNode = treeNode.right;
}
}
}
// 用非递归的方法进行中序遍历
public void zhongxuFeiDigui(TreeNode treeNode) {
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
stack.push(treeNode);
treeNode = treeNode.left;
}
if (!stack.isEmpty()) {
treeNode = stack.pop();
zhongxuNumList.add(treeNode.val);
treeNode = treeNode.right;
}
}
}
// 用非递归的方法进行后序遍历
public void houxuFeiDigui(TreeNode treeNode) {
Stack<TreeNode> stack = new Stack<TreeNode>();
while (treeNode != null || !stack.isEmpty()) {
while (treeNode != null) {
stack.push(treeNode);
treeNode = treeNode.left;
}
boolean tag = true;
TreeNode preNode = null; // 前驱节点
while (!stack.isEmpty() && tag == true) {
treeNode = stack.peek();
if (treeNode.right == preNode) { // 之前访问的为空节点或是栈顶节点的右子节点
treeNode = stack.pop();
houxuNumList.add(treeNode.val);
if (stack.isEmpty()) {
return;
} else {
preNode = treeNode;
}
} else {
treeNode = treeNode.right;
tag = false;
}
}
}
}