题目
- 构建二叉树并实现前序、后序、中序遍历,查找最大结点及最小结点
解法
public class BSTNode<T extends Comparable<T>> {
T key;
BSTNode<T> left;
BSTNode<T> right;
BSTNode<T> parent;
public BSTNode(T key, BSTNode<T> parent, BSTNode<T> left, BSTNode<T> right) {
this.key = key;
this.parent = parent;
this.left = left;
this.right = right;
}
}
/**
* 前序遍历 根左右
*
* @param tree
*/
public void preOrder(BSTNode<T> tree) {
if (tree != null) {
System.out.println(tree.key);
preOrder(tree.left);
preOrder(tree.right);
}
}
/**
* 中序遍历 左中右
*
* @param tree
*/
public void inOrder(BSTNode<T> tree) {
if (tree != null) {
inOrder(tree.left);
System.out.println(tree.key);
inOrder(tree.right);
}
}
/**
* 后序遍历 左右中
*
* @param tree
*/
public void postOrder(BSTNode<T> tree) {
if (tree != null) {
postOrder(tree.left);
postOrder(tree.right);
System.out.println(tree.key);
}
}
/**
* 查找最大结点
*
* @param tree
* @return
*/
public BSTNode<T> findMax(BSTNode<T> tree) {
if (tree == null) return null;
while (tree.right != null) {
tree = tree.right;
}
return tree;
}
/**
* 查找最小结点
*
* @param tree
* @return
*/
public BSTNode<T> findMinimum(BSTNode<T> tree) {
if (tree == null) return null;
while (tree.left != null) {
tree = tree.left;
}
return tree;
}