层次遍历二叉树和采用栈的方式遍历二叉树

	//中序遍历非递归
	@Override
	public void inOrderByStack() {
		System.out.println("中序遍历非递归操作");
		//创建栈
		Deque<Node> stack=new LinkedList<Node>();
		Node current=root;
		while(current!=null||!stack.isEmpty()) {
			while(current!=null) {
				stack.push(current);
				current=current.leftChild;			
			}
			if(!stack.isEmpty()) {
				current=stack.pop();
				System.out.println(current.value+"");
				current=current.rightChild;
			}
		}
		System.out.println();		
	}
    //层次遍历二叉树
	private void preOrderByStack(Node root2) {
		if(root==null) {
			return;
		}
		Queue<Node> queue=new LinkedList<Node>();
		queue.add(root);
		while(queue.size()!=0) {
			int len=queue.size();
			for(int i=0;i<len;i++) {
				Node temp=queue.poll();
				System.out.println(temp.value);
				if(temp.leftChild!=null) {
					queue.add(temp.leftChild);
				}
				if(temp.rightChild!=null) {
					queue.add(temp.rightChild);
				}
			}
		}
	}

层次遍历二叉树:一层一层地去遍历

采用栈的方式遍历二叉树:采用栈先进先出的特征

猜你喜欢

转载自blog.csdn.net/shujuelin/article/details/86490318