1.前序遍历
1.递归
public List<Integer> preOrder(TreeNode root){
List<Integer> list = new LinkedList<>();
if(root==null){
return list;
}
list.add(root.val);
list.addAll(preOrder(root.left));
list.addAll(preOrder(root.right));
return list;
}
2.迭代
public List<Integer> preOrderLoop(TreeNode root){
List<Integer> list = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if(root!=null){
stack.push(root);
}
while(!stack.isEmpty()){
TreeNode current = stack.pop();
list.add((Integer) current.val);
if(current.right!=null){
stack.push(current.right);
}
if(current.left!=null){
stack.push(current.left);
}
}
return list;
}
2.中序遍历
1.递归
public List<Integer> midOrder(TreeNode root){
List<Integer> list = new LinkedList<>();
if(root==null){
return list;
}
list.addAll(midOrder(root.left));
list.add(root.val);
list.addAll(midOrder(root.right));
return list;
}
2.迭代
public List<Integer> midOrderLoop(TreeNode root){
List<Integer> list = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while(current!=null){
stack.push(current);
current = current.left;
}
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
list.add(temp.val);
TreeNode node = temp.right;
while(node!=null){
stack.push(node);
node = node.left;
}
}
return list;
}
3.后序遍历
1.递归
public List<Integer> backOrder(TreeNode root){
List<Integer> list = new LinkedList<>();
if(root==null){
return list;
}
list.addAll(backOrder(root.left));
list.addAll(backOrder(root.right));
list.add(root.val);
return list;
}
2.迭代
public List<Integer> backOrderLoop(TreeNode root){
LinkedList<Integer> list = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if(root!=null){
stack.push(root);
}
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
list.addFirst((Integer)temp.val);
if(temp.left!=null){
stack.push(temp.left);
}
if(temp.right!=null){
stack.push(temp.right);
}
}
return list;
}