迭代实现前序遍历
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()) {
while(root != null){
stack.push(root);
list.add(root.val);
root = root.left;
}
root = stack.pop();
if(root.right != null) {
root = root.right;
}else{
root = null;
}
}
return list;
}
迭代实现中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
while(root != null || !stack.isEmpty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
if(root.right == null) {
root = null;
}else{
root = root.right;
}
}
return list;
}
迭代实现后序遍历
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pre = null;
while(root != null || !stack.isEmpty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if(root.right == null || root.right == pre) {
list.add(root.val);
pre = root;
root = null;
}else{
stack.push(root);
root = root.right;
}
}
return list;
}
|