递归算法遍历
/**
* 前序遍历
*/
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;
}
list.add(rootNode.val);
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);
list.add(rootNode.val);
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);
list.add(rootNode.val);
}
复制代码
迭代算法遍历
前序遍历
思路与算法
我们也可以用迭代的方式实现方法一的递归函数,两种方式是等价的,区别在于递归的时候隐式地维护了一个栈,而我们在迭代的时候需要显式地将这个栈模拟出来,其余的实现与细节都相同,具体可以参考下面的代码。
、
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) {
arrayList.add(rootNode.val);
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) {
res.add(root.val);
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();
arrayList.add(root.val);
root = root.right;
}
return arrayList;
复制代码
【参考】
【1】leetcode