二叉树遍历
定义二叉树结构
package com.vleus.algorithm.binary_tree;
/**
* @author vleus
* @date 2021年05月25日 22:53
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
二叉树的中序遍历(指根的位置)
遍历顺序为:左->根->右;
那么遍历结果应该为:DBGEACF;
//中序遍历
public static void printTreeInOrder(TreeNode root) {
if (root == null) {
return;
}
printTreeInOrder(root.left);
System.out.println(root.val + "\t"); //先打印根
printTreeInOrder(root.right);
}
二叉树的先序遍历
遍历顺序为:根->左->右;
那么遍历结果应该为:ABDEGCF
//先序遍历
public static void printTreePreOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.println(root.val + "\t"); //先打印根
printTreePreOrder(root.left);
printTreePreOrder(root.right);
}
二叉树的后序遍历
遍历顺序为:左->右->根;
那么遍历结果应该为:DGEBFCA
//后序遍历
public static void printTreePostOrder(TreeNode root) {
if (root == null) {
return;
}
printTreePostOrder(root.left);
printTreePostOrder(root.right);
System.out.println(root.val + "\t"); //先打印根
}
二叉树的层序遍历
思路:利用队列实现
//层序遍历
public static void printTreeLevelOrder(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<>();
//先把根节点放入队列
queue.offer(root);
//只要队列不为空,就一直出队
while (!queue.isEmpty()) {
TreeNode curNode = queue.poll();
System.out.println(curNode.val + "\t");
//将子节点接入队列
if (curNode.left != null) {
queue.offer(curNode.left);
}
if (curNode.right != null) {
queue.offer(curNode.right);
}
}
}
二叉搜索树
二叉搜索树也称为有序二叉查找树,满足二叉查找树的一般性质,是指一棵空树具有如下特征:
- 任意节点左子树如果不为空,那么左子树的节点的值均小于根节点的值;
- 任意节点右字数如果不为空,则右字数中节点的值均大于根节点的值;
- 任意节点的左右子树,也分别是二叉搜索树;
- 没有键值相等的节点;