二叉树的数据结构:
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
前序遍历
public static List<Integer> preOrderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
while (root != null) {
res.add(root.val);
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
root = stack.pop().right;
}
}
return res;
}
中序遍历
private static List<Integer> inOrderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
do {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
res.add(stack.peek().val);
root = stack.pop().right;
}
} while (!stack.isEmpty() || root != null);
return res;
}
中序遍历二(20191123)
public static List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
res.add(stack.peek().val);
root = stack.pop().right;
}
}
return res;
}