import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeIteration {
public static void main(String[] args) {
//构造指定节点个数的二叉树
BinaryTree root = buildBinaryTree(99);
iterateBinaryTree(root);
iterateBinaryTree2(root);
}
/**
* 先遍历所有左节点,后所有右节点方式
* @param root 根节点
*/
public static void iterateBinaryTree(BinaryTree root) {
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
BinaryTree curNode = root;
while(null != curNode || !queue.isEmpty()) {
while(null != curNode) {
//输出当前遍历到的节点的值,并保存该节点,最后将当前节点引用指向左孩子,继续循环
System.out.println(curNode.getValue());
queue.offer(curNode);
curNode = curNode.getLeft();
}
//根节点开始遍历完所有左孩子后,开始依次遍历访问过的节点的右孩子
if(!queue.isEmpty()) {
curNode = queue.poll();
curNode = curNode.getRight();
}
}
}
/**
* 依次输出左节点,右节点,逐层递进
* @param root 根节点
*/
public static void iterateBinaryTree2(BinaryTree root) {
Queue<BinaryTree> queue = new LinkedList<BinaryTree>();
BinaryTree curNode = root;
queue.offer(curNode);
while(!queue.isEmpty()) {
BinaryTree temp = queue.poll();
System.out.println(temp.getValue());
if(null != temp.getLeft()) {
queue.offer(temp.getLeft());
}
if(null != temp.getRight()) {
queue.offer(temp.getRight());
}
}
}
/**
* 构造二叉树
*
* @param length 二叉树节点个数
* @return
*/
public static BinaryTree buildBinaryTree(int length) {
List<BinaryTree> treeList = new ArrayList<BinaryTree>();
for (int i = 0; i <length ; i++) {
treeList.add(new BinaryTree(i));
}
BinaryTree root = treeList.get(0);
for (int index = 0; index < treeList.size()/2; index++) {
if(2*index+2 < treeList.size()) {
treeList.get(index).setRight(treeList.get(2*index+2));
}
treeList.get(index).setLeft(treeList.get(2*index+1));
}
return root;
}
}
/**
*
*二叉树结构
*/
class BinaryTree {
private int value;//节点值
private BinaryTree left;//左节点
private BinaryTree right;//右节点
public BinaryTree() {}
public BinaryTree(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public BinaryTree getLeft() {
return left;
}
public void setLeft(BinaryTree left) {
this.left = left;
}
public BinaryTree getRight() {
return right;
}
public void setRight(BinaryTree right) {
this.right = right;
}
}
二叉树遍历
最新推荐文章于 2024-01-27 15:36:29 发布