void preOrder(BTNode * head) {
if (head == null) return ;
Stack<Node> stack = new Stack<BTNode *>();
stack.push(head);
while (!stack.isEmpty()){
head= stack.top();
cout<<head->data<<" ";
stack.pop();
if(head.right != null) stack.push(head.right);
if(head.left != null) stack.push(head.left);
}
}
void inOrder(BTNode * head) {
if (head == null) return ;
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null){
if (head != null){
stack.push(head);
head = head.left;
} else{
head = stack.pop();
cout<<head->data<<" ";
head = head.right;
}
}
}
void postOrder(BTNode * head){
if (head == null) return ;
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()){
head = s1.pop();
s2.push(head);
if(head.left != null) s1.push(head.left);
if (head.right != null) s1.push(head.right);
}
while (!s2.isEmpty()){
BTNode * cur=s2.pop();
cout<<cur->data<<" ";
}
}
非递归方式先序+中序+后序遍历二叉树
最新推荐文章于 2021-03-25 16:52:20 发布