您的位置:首页 > 其它

二叉树的遍历(递归,非递归,层次)

2017-01-17 17:03 489 查看
非递归中序遍历:

// 对于结点root;
// 1)若其结点不为空,则将root入栈并将root的左孩子置为当前的root,然后对当前结点root再进行相同的处理;
// 2)若其左孩子为空,则取栈顶元素并进行出栈操作,访问该节点,然后将当前的root置为栈顶结点的右孩子
// 3)直到p为null并且栈为空则遍历结束
// iterative
public void inorderTraversal2(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
while(root!=null || !stack.isEmpty()){
while( root!= null){
stack.push( root);
root = root. left;
}
if (! stack.isEmpty()) {
TreeNode topNode = stack.peek();
System. out.println( " "+ topNode. key);
stack.pop();

if ( null != topNode. right) {
root= topNode. right;
}
}
}
}

// 非递归中序遍历----这种不容易记忆和编写
public void inorder_iterative_tree_walk(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
while( root!= null || ! stack.isEmpty()){
if ( root != null) {
stack.push( root);
root = root. left;
} else{
TreeNode top = stack.peek();
System. out.print( top. key+ " ");
stack.pop();
root = top. right; //访问右子树
}
}
}

// 中序遍历---递归
public void inorder_tree_walk( TreeNode x){
if ( x!= null) {
inorder_tree_walk( x. left);
System. out.print( x. key + " ");
inorder_tree_walk( x. right);
}
}

// 前序遍历---递归
public void preorder_tree_walk( TreeNode x){
if ( x!= null) {
System. out.print( x. key + " ");
preorder_tree_walk( x. left);
preorder_tree_walk( x. right);
}
}

// 前序遍历---非递归
public void preorder_iterative_tree_walk(TreeNode x){
Stack<TreeNode > stack = new Stack<>();
stack.push( x);
while(! stack.isEmpty()){
TreeNode top = stack.peek();
System. out.print( top. key+ " ");
stack.pop();

if( top. right!= null){
stack.push( top. right);
}

if ( top. left!= null) {
stack.push( top. left);
}
}
}

// 后序遍历---递归版
public void postorder_tree_walk(TreeNode x){
if ( x!= null) {
postorder_tree_walk( x. left);
postorder_tree_walk( x. right);
System. out.print( x. key+ " ");
}
}

// 后序遍历非递归
// 1.push根结点到第一个栈s中
// 2.从第一个栈s中弹出一个结点,并将其push到第二个output中
// 3.然后push结点的左孩子和右孩子到第一个栈s中
// 4.重复2,3过程直到栈s为空
public void postorder_iterative_tree_walk(TreeNode x){
if ( x== null) return ;
Stack<TreeNode> stack = new Stack<>();
Stack<TreeNode> output = new Stack<>();
stack.push( x);
while(! stack.isEmpty()){
TreeNode top = stack.peek();
output.push( top);
stack.pop();

if ( top. left!= null) {
stack.push( top. left);
}
if ( top. right != null) {
stack.push( top. right);
}
}

while(! output.isEmpty()){
System. out.print( output.peek(). key+ " ");
output.pop();
}
}

// 层次遍历
public void level_order_tree_walk(TreeNode x){
if ( x== null) return ;
//java中队列的调用方法和c++的不一样
LinkedBlockingQueue<TreeNode> queue = new LinkedBlockingQueue();
queue.add( x);
while(! queue.isEmpty()){
TreeNode top = queue.peek();
System. out.print( top. key+ " ");
queue.poll(); //移除元素
if ( top. left != null) {
queue.offer( top. left);
}
if ( top. right != null) {
queue.offer( top. right);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 递归 遍历
相关文章推荐