递归法
前序遍历
class Preorder {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
preorder(root, result);
return result;
}
public void preorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
result.add(root.val);
preorder(root.left, result);
preorder(root.right, result);
}
}
中序遍历
class Inorder {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
inorder(root, result);
return result;
}
public void inorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}
后序遍历
class Postorder {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
postorder(root, result);
return result;
}
public void postorder(TreeNode root, List<Integer> result) {
if(root == null) {
return;
}
postorder(root.left, result);
postorder(root.right, result);
result.add(root.val);
}
}
迭代法
前序遍历
class Preorder {
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) {
return new ArrayList<Integer>();
}
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop(); //每次循环只从栈中出来一个节点,保证了右节点晚于左节点出来
result.add(node.val);
if(node.right != null) {
stack.push(node.right);
}
if(node.left != null) {
stack.push(node.left);
}
}
return result;
}
}
中序遍历
class Inorder {
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) {
return new ArrayList<Integer>();
}
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
//stack.push(root);
TreeNode curr = root; //中序和后序遍历需要借助辅助节点进行遍历
while(curr != null || !stack.isEmpty()) { //curr==null && stack.isEmpty()时表示搜索完毕
if(curr != null) { //先搜索左子树
stack.push(curr);
curr = curr.left;
}else {
curr = stack.pop();
result.add(curr.val);
curr = curr.right;
}
}
return result;
}
}
后序遍历
class Postorder {
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null) {
return new ArrayList<Integer>();
}
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
TreeNode isSearched = null; //辅助记录已经搜索过的右节点(右子树)
// 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
while(curr != null || !stack.isEmpty()) {
if(curr != null) {
stack.push(curr);
curr = curr.left;
}else {
curr = stack.pop();
//判断右子树是否存在
//注意识别是否搜索过了右子树
if(curr.right != null && isSearched != curr.right) { //右子树存在 并且 右节点还没搜索过
stack.push(curr); //存在右子树,就把中间结点 再 放进栈中
curr = curr.right;
}else { //右子树不存在 或者 右子树已经搜索过
result.add(curr.val);
isSearched = curr;
curr = null; //将curr置为null,表示当前的结点以及子树已经搜索完毕
}
}
}
return result;
}
}