二叉树
二叉树是每个结点最多有两个子树的树结构,二叉树常被用于实现二叉查找树和二叉堆
定义树节点结构
private static class TreeNode<T>{
T val;
TreeNode left;
TreeNode right;
TreeNode(T val){
this.val = val;
}
}
创建二叉树
public static TreeNode creatBinaryTree(LinkedList<T> list){
TreeNode root = null;
if(list == null || list.isEmpty()) {
reutrn root;
}
T val = list.removeFirst();
if(val != null) {
root = new TreeNode(val);
root.left = creatBinaryTree(list);
root.right = creatBinaryTree(list);
}
return root;
}
前序遍历
按照 根-左-右 顺序递归遍历
public void preOrder(TreeNode root) {
if(root == null) {
return;
}
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
中序遍历
public void inOrder(TreeNode root) {
if(root == null) {
return;
}
preOrder(root.left);
System.out.println(root.val);
preOrder(root.right);
}
后序遍历
public void postOrder(TreeNode root) {
if(root == null) {
return;
}
preOrder(root.left);
preOrder(root.right);
System.out.println(root.val);
}
二叉树遍历非递归实现
非递归使用最多的数据结构就是栈,栈具有先天的递归特性,以前序遍历为例:
public void preOrder(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null || !stack.isEmpty()) {
// 左孩子入栈
while(node != null) {
System.out.println(node.val);
stack.push(node);
node = node.left;
}
//左孩子为空, 弹出栈顶, 访问右孩子
if(!stack.isEmpty()) {
node = stack.pop();
node = node.right;
}
}
}
二叉树的层序遍历
public void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.println(node.val);
// 左孩子入队列
if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
}