一、二叉树的遍历
二叉树的遍历分为先序遍历,中序遍历,后序遍历:先序遍历历即为 中左右, 中序遍历为 左中右, 后序遍历为 左右中。
递归方式比较简单和常见,非递归采用栈来实现
二、代码:
二叉树的定义:
/**
* @author 作者 : xcy
* @version 创建时间:2016年11月20日 下午8:21:03
* 类说明
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
遍历的方法:
package T12;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author 作者 : xcy
* @version 创建时间:2016年12月1日 下午8:59:08
* 类说明
*/
public class t94 {
public static List<Integer> re = new ArrayList<Integer>();
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
n1.right = n2;
n2.left = n3;
List<Integer> re = postorderTraversalNDG(n1);
for (Integer i : re) {
System.out.println(i);
}
}
// 中序 递归
public static List<Integer> inorderTraversalDG(TreeNode root) {
if (root != null) {
inorderTraversalDG(root.left);
re.add(root.val);
inorderTraversalDG(root.right);
}
return re;
}
// 中序 用栈实现非递归遍历
public static List<Integer> inorderTraversalNDG(TreeNode root) {
Stack<TreeNode> stack = null;
TreeNode temp = root;
stack = new Stack<TreeNode>();
while (temp != null || !stack.isEmpty()) {
while (temp != null) {
stack.push(temp);
temp = temp.left;
}
TreeNode node = stack.pop();
re.add(node.val);
temp = node.right;
}
return re;
}
// 先序 递归
public static List<Integer> preorderTraversalDG(TreeNode root) {
if (root != null) {
re.add(root.val);
inorderTraversalDG(root.left);
inorderTraversalDG(root.right);
}
return re;
}
// 先序 用栈实现非递归遍历
public static List<Integer> preorderTraversalNDG(TreeNode root) {
Stack<TreeNode> stack = null;
TreeNode temp = root;
stack = new Stack<TreeNode>();
while (temp != null || !stack.isEmpty()) { // 左孩子
while (temp != null) { // 压栈前访问
re.add(temp.val);
stack.push(temp);
temp = temp.left;
}
TreeNode node = stack.pop();
temp = node.right;
}
return re;
}
// 后序 递归
public static List<Integer> postorderTraversalDG(TreeNode root) {
if (root != null) {
inorderTraversalDG(root.left);
inorderTraversalDG(root.right);
re.add(root.val);
}
return re;
}
// 后序 用栈实现非递归遍历
public static List<Integer> postorderTraversalNDG(TreeNode root) {
Stack<TreeNode> stack = null;
TreeNode temp = root;
stack = new Stack<TreeNode>();
// 用中间栈存储逆后序遍历结果
Stack<TreeNode> out = new Stack<TreeNode>();
while (temp != null || !stack.isEmpty()) { // 孩子
while (temp != null) { // 压栈前访问
out.push(temp);
stack.push(temp);
temp = temp.right;
}
temp = stack.pop();
temp = temp.left;
}
while (!out.empty()) {
TreeNode o = out.pop();
re.add(o.val);
}
return re;
}
}