前序遍历
递归
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
preorder(root);
return list;
}
public void preorder(TreeNode root) {
if (root == null) {
return;
}
list.add(root.val);
preorder(root.left);
preorder(root.right);
}
}
非递归
思路:利用栈,先push右子结点,再push左子结点,先pop的就是左子结点
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return ret;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
ret.add(node.val);
if (node.right != null) {
stack.add(node.right);
}
if (node.left != null) {
stack.add(node.left);
}
}
return ret;
}
}
中序遍历
题目:94. 二叉树的中序遍历
递归
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inorder(root);
return list;
}
public void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
非递归
思路:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if (root == null) return ret;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
ret.add(node.val);
root = node.right;
}
return ret;
}
}
后序遍历
题目:45. 二叉树的后序遍历
递归
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
postorder(root);
return list;
}
public void postorder(TreeNode root) {
if (root == null) {
return;
}
postorder(root.left);
postorder(root.right);
list.add(root.val);
}
}
非递归
class Solution {
private List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return list;
}
Deque<TreeNode> stack = new ArrayDeque<>();
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) {
list.add(root.val);
prev = root;
root = null;
} else {
stack.push(root);
root = root.right;
}
}
return list;
}
}