Java实现二叉树的递归、非递归,前序遍历、中序遍历、后序遍历;以及层次遍历
递归前序遍历
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> preOrder(TreeNode root) {
if (root != null) {
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
return list;
}
非递归前序遍历
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> preOrder2(TreeNode root) {
Stack<TreeNode> stack = new Stack();
while (root != null || !stack.empty()) {
while (root != null) {
stack.push(root);
list.add(root.val);
root = root.left;
}
if (!stack.empty()) {
root = stack.pop();
root = root.right;
}
}
return list;
}
递归中序遍历
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> preOrder(TreeNode root) {
if (root != null) {
preOrder(root.left);
list.add(root.val);
preOrder(root.right);
}
return list;
}
非递归中序遍历
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> preOrder2(TreeNode root) {
Stack<TreeNode> stack = new Stack();
while (root != null || !stack.empty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.empty()) {
root = stack.pop();
list.add(root.val);
root = root.right;
}
}
return list;
}
递归后序遍历
ArrayList<Integer> list = new ArrayList();
public ArrayList<Integer> preOrder(TreeNode root) {
if (root != null) {
preOrder(root.left);
preOrder(root.right);
list.add(root.val);
}
return list;
}
非递归后序遍历
public ArrayList<Integer> preOrder2(TreeNode root) {
ArrayList<Integer> list = new ArrayList();
Stack<TreeNode> stack = new Stack();
TreeNode r = null;
while (root != null || stack.empty()) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.peek();
if (root.right != null && root.right != r) {
root = root.right;
stack.push(root);
root = root.left;
} else {
root = stack.pop();
list.add(root.val);
r = root;
root = null;
}
}
}
return list;
}
层次遍历
public ArrayList<Integer> preOrder2(TreeNode root) {
ArrayList<Integer> list = new ArrayList();
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
while (root != null || !queue.isEmpty()) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
return list;
}