一、前序遍历
1.1、前序遍历递归版本
private void preOrder(ListNode node) {
if(node == null)
return;
inOrder(node.left);
System.out.print(node.key+" ");
inOrder(node.right);
}
1.2、前序遍历非递归版本
public List<String> preorderTraversal() {
if(root == null){
return null;
}
List<String> list = new LinkedList<String>();
ListNode node = root;
Stack<ListNode> stack = new Stack<ListNode>();
stack.push(node);
while(stack.empty() == false){
if(node != null){
list.add(node.key);
stack.push(node);
node=node.left;
}else{
node = stack.pop();
node = node.right;
}
}
return list;
}
二、中许遍历
2.1、中序遍历递归版本
private void inOrder(ListNode node) {
if(node == null)
return;
inOrder(node.left);
System.out.print(node.key+" ");
inOrder(node.right);
}
2.2、中序遍非递归版本
public List<String> inorderTraversal() {
if(root == null){
return null;
}
List<String> list = new LinkedList<String>();
ListNode node = root;
Stack<ListNode> stack = new Stack<ListNode>();
stack.push(node);
while(stack.empty() == false){
if(node != null){
stack.push(node);
node=node.left;
}else{
node = stack.pop();
list.add(node.key);
node = node.right;
}
}
return list;
}
三、后序遍历
3.1、后序遍历递归版本
private void postOrder(ListNode node) {
if(node == null)
return;
inOrder(node.left);
inOrder(node.right);
System.out.print(node.key+" ");
}
3.2、后序遍历非递归版本
public void postOrder(){
Stack<ListNode> stack = new Stack<ListNode>();
ListNode curNode = root;
ListNode lastNode = null;
while(!stack.isEmpty() || curNode != null){
if(curNode != null){
stack.push(curNode);
curNode = curNode.left;
}else{
curNode = stack.peek();
if(curNode.right!=null && lastNode != curNode.right){
curNode = curNode.right;
}else{
System.out.println(curNode.val);
lastNode = curNode;
stack.pop();
curNode = null;
}
}
}
}