void PreOrder(root){
if(root!=null){
visit(root);
PreOrder(root.left);
PreOrder(root.right);
}
}
void InOrder(root){
if(root!=null){
InOrder(root.left);
visit(root);
InOrder(root.right);
}
}
void PostOrder(root){
if(root!=null){
PostOrder(root.left);
PostOrder(root.right);
visit(root);
}
}
以上三种遍历的时间复杂度都是O(n),因为每个节点都只访问过一次。
void InOrder(root){
TreeNode p=root;//p是遍历指针
while(p||!stack.isEmpty()){//p非空或者栈中还有元素就循环
if(p){
stack.push(p);
p=p.leaf;
}else{
TreeNode q=stack.pop();
visit(q);
p=p.right;
}
}
}
void LevelOrder(root){
queue.offer(root);
while(!queue.isEmpty()){
TreeNode p=queue.poll();
visit(p);
if(root.left!=null)
queue.offer(root.left);
if(root.right!=null)
queue.offer(root.right);
}
}
原文:https://www.cnblogs.com/k-will/p/12733064.html