package org.algo;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Stack;
/**
* 树深度/广度遍历
* Created with IntelliJ IDEA.
* Date: 16-3-21
* Time: 下午5:16
* To change this template use File | Settings | File Templates.
*/
public class TreeTraversal {
/**
* 树节点
*/
public static class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int value) {
this.value = value;
}
public void visit() {
System.out.print(value + " ");
}
}
/**
* 深度遍历
* @param root
*/
public static void breadth1stTraversal(TreeNode root) {
if (root == null) {
return;
}
Queue<TreeNode> treeNodeQueue = new ArrayDeque<TreeNode>();
treeNodeQueue.add(root);
while (!treeNodeQueue.isEmpty()) {
TreeNode node = treeNodeQueue.poll();
node.visit();
if (node.left != null) {
treeNodeQueue.add(node.left);
}
if (node.right != null) {
treeNodeQueue.add(node.right);
}
}
}
/**
* 广度遍历
* @param root
*/
public static void depth1stTraversal(TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> treeNodeStack = new Stack<TreeNode>();
treeNodeStack.push(root);
while (!treeNodeStack.isEmpty()) {
TreeNode node = treeNodeStack.pop();
node.visit();
if (node.right != null) {
treeNodeStack.push(node.right);
}
if (node.left != null) {
treeNodeStack.push(node.left);
}
}
}
/**
* 构建测试用的树
* 1
* / \
* 2 3
* / \
* 4 5
* \
* 6
* @return
*/
public static TreeNode buildTestTree() {
TreeNode treeNode1 = new TreeNode(1);
TreeNode treeNode2 = new TreeNode(2);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(4);
TreeNode treeNode5 = new TreeNode(5);
TreeNode treeNode6 = new TreeNode(6);
treeNode1.left = treeNode2;
treeNode1.right = treeNode3;
treeNode2.left = treeNode4;
treeNode2.right = treeNode5;
treeNode5.right = treeNode6;
return treeNode1;
}
/**
* 结果是:
* 1 2 3 4 5 6
*/
public static void testBreadth1stTraversal() {
breadth1stTraversal(buildTestTree());
}
/**
* 结果是:
* 1 2 4 5 6 3
*/
public static void testDepth1stTraversal() {
depth1stTraversal(buildTestTree());
}
/**
* 测试例程
* @param args
*/
public static void main(String[] args) {
testBreadth1stTraversal();
System.out.println();
testDepth1stTraversal();
}
}
用java实现数的深度遍历和广度遍历
最新推荐文章于 2023-08-22 05:30:00 发布