/**
* 先顺遍历,中,左,右
* @param node
*/
public static void travelTreeFirst(TreeNode node) {
if (node == null) {
return;
}
printNode(node);
travelTreeFirst(node.getLeftChild());
travelTreeFirst(node.getRightChild());
}
/**
* 中序遍历 左 中 右
* @param node
*/
public static void travelTreeMid(TreeNode node) {
if (node == null) {
return;
}
travelTreeMid(node.getLeftChild());
printNode(node);
travelTreeMid(node.getRightChild());
}
/**
* 后序遍历
* @param node
*/
public static void travelTreeLast(TreeNode node) {
if (node == null) {
return;
}
travelTreeLast(node.getLeftChild());
travelTreeLast(node.getRightChild());
printNode(node);
}
private static void printNode(TreeNode node) {
Log.d("tree", "tree node=" + node.getData()+"--");
}
三种遍历方法
public class TreeNode<T> {
T data;
TreeNode<T> leftChild;
TreeNode<T> rightChild;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public TreeNode<T> getLeftChild() {
return leftChild;
}
public void setLeftChild(TreeNode<T> leftChild) {
this.leftChild = leftChild;
}
public TreeNode<T> getRightChild() {
return rightChild;
}
public void setRightChild(TreeNode<T> rightChild) {
this.rightChild = rightChild;
}
}
节点