前序遍历
/**
* 前序遍历二叉树
*
* @param rNode 根node
*/
public static void preOrder(TreeNode rNode) {
if (rNode != null) {
//nodeList.add(rNode);
System.out.println(rNode.value);
preOrder(rNode.left);
preOrder(rNode.right);
}
}
中序遍历
/**
* 中序遍历 递归 & 非递归
*/
public class InOrderTree {
/**
* 非递归遍历二叉树
*
* @param root 根节点
*/
public static void inOrderStack(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop(); //出栈
System.out.println(root.value);//访问
root = root.right; //如果有右子树,递归访问右子树
}
}
/**
* 递归遍历二叉树
*
* @param root 根节点
*/
public static void recursionInTree(TreeNode root) {
if (root == null) return;
recursionInTree(root.left);
System.out.println(root.value);
recursionInTree(root.right);
}
}
后序遍历
/**
* 后序遍历二叉树
*
* @param rNode 根node
*/
public static void afterOrder(TreeNode rNode) {
if (rNode != null) {
afterOrder(rNode.left);
afterOrder(rNode.right);
//nodeList.add(rNode);
System.out.println(rNode.value);
}
}