·  阅读 318

# 递归算法遍历

``````/**
* 前序遍历
*/
public static int[] preTraversalTree(TreeNode rootNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
preOrder(rootNode, arrayList);
return arrayList.stream().mapToInt(Integer::intValue).toArray();
}

/**
* 前序遍历
*/
public static void preOrder(TreeNode rootNode, ArrayList<Integer> list) {
if (rootNode == null) {
return;
}
preOrder(rootNode.left, list);
preOrder(rootNode.right, list);
}

/**
* 中序遍历
*
* @param rootNode
* @param list
*/
public static int[] inTraversalTree(TreeNode rootNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
inOrder(rootNode, arrayList);
return arrayList.stream().mapToInt(Integer::intValue).toArray();
}

/**
* 中序遍历
*
* @param rootNode
* @param list
*/
public static void inOrder(TreeNode rootNode, ArrayList<Integer> list) {
if (rootNode == null) {
return;
}
inOrder(rootNode.left, list);
inOrder(rootNode.right, list);
}

/**
* 后序遍历
*
* @param rootNode
*/
public static int[] postTraversalTree(TreeNode rootNode) {
ArrayList<Integer> arrayList = new ArrayList<>();
postOrder(rootNode, arrayList);
return arrayList.stream().mapToInt(Integer::intValue).toArray();
}

/**
* 后序遍历
*
* @param rootNode
* @param list
*/
public static void postOrder(TreeNode rootNode, ArrayList<Integer> list) {
if (rootNode == null) {
return;
}
postOrder(rootNode.left, list);
postOrder(rootNode.right, list);
}

# 迭代算法遍历

## 前序遍历

``````public static List<Integer> preOrderTraverse(TreeNode rootNode) {
Stack<TreeNode> stack = new Stack<>();
ArrayList<Integer> arrayList = new ArrayList<>();
while (rootNode != null || !stack.isEmpty()) {
while (rootNode != null) {
stack.push(rootNode);
rootNode = rootNode.left;
}
TreeNode pop = stack.pop();
rootNode = pop.right;
}
return arrayList;
}

## 后序遍历

``````public static List<Integer> postOrderTraverse(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null) {
return res;
}

Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (root.right == null || root.right == prev) {
prev = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return res;
}

## 中序遍历

``````Stack<TreeNode> stack = new Stack<>();
ArrayList<Integer> arrayList = new ArrayList<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return arrayList;

【参考】
【1】leetcode