Skip to content

Commit

Permalink
二分搜索树层序遍历levelOrder()
Browse files Browse the repository at this point in the history
  • Loading branch information
liusishan committed Feb 20, 2019
1 parent 197bd28 commit 120f35d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
26 changes: 22 additions & 4 deletions 06-Binary-Search-Tree/01-Binary-Search-Tree-Basics/src/BST.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.StringStack;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
Expand Down Expand Up @@ -95,16 +97,16 @@ private void preOrder(Node node) {
}

// 二分搜索树的非递归前序遍历
public void preOrderNR(){
public void preOrderNR() {
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
while (!stack.isEmpty()) {
Node cur = stack.pop();
System.out.println(cur.e);

if(cur.right!=null)
if (cur.right != null)
stack.push(cur.right);
if (cur.left!=null)
if (cur.left != null)
stack.push(cur.left);
}
}
Expand Down Expand Up @@ -141,6 +143,22 @@ private void postOrder(Node node) {
System.out.println(node.e);
}

// 二分搜索树的层序遍历
public void levelOrder() {

Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
Node cur = queue.remove();
System.out.println(cur.e);

if (cur.left != null)
queue.add(cur.left);
if (cur.right != null)
queue.add(cur.right);
}
}

@Override
public String toString() {
StringBuilder res = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public static void main(String[] args) {

bst.postOrder();
System.out.println();
bst.preOrderNR();
System.out.println();
// bst.preOrder();
// System.out.println(bst);
}
Expand Down

0 comments on commit 120f35d

Please sign in to comment.