现有一颗如下图所示的二叉树:
其遍历的各种方式如下:
构造一颗如下图所示的二叉树,用java实现其前序,中序,后序遍历
注意二叉树节点的定义如下:
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
递归实现:
// 用递归的方法进行先序遍历
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);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
非递归实现:
// 用非递归的方法进行先序遍历
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;
}
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
运行结果如下: