首先会介绍树的概念,然后再介绍二叉树,二叉树是树的一种
一、树的基础概念
概念主要分为两块,第一块是对树结构的认识,包括形式和如何组织。第二块则是了解树中一些专用名词,比如度,深度之类的
(1)树是一种非线性的数据结构。把它叫做树是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。同理,作为“树”,它只有一个根节点,且同级节点中没有相交关系
(2)树有三种表示方法,其中最常用的是【孩子兄弟表示法】
-------重要-------------------------
结点的度:一个结点含有子树的个数称为该结点的度
树的度:一棵树中,所有结点度的最大值称为树的度
叶子结点或终端结点:度为0的结点称为叶子结点; 如上图:B、C、H、I…等节点为叶结点
双亲结点或父结点:若一个结点含有子结点,则这个结点称为其子结点的父结点
孩子结点或子结点:一个结点含有的子树的根结点称为该结点的子结点
根结点:一棵树中,没有双亲结点的结点
结点的层次/深度:从根开始定义起,根为第1层,根的子结点为第2层,以此类推
树的高度或深度:树中结点的最大层次
-------了解-------------------------
非终端结点或分支结点:度不为0的结点
兄弟结点:具有相同父结点的结点互称为兄弟结点
堂兄弟结点:双亲在同一层的结点互为堂兄弟
结点的祖先:从根到该结点所经分支上的所有结点
子孙:以某结点为根的子树中任一结点都称为该结点的子孙
森林:由m(m>=0)棵互不相交的树组成的集合称为森林
二、二叉树
首先介绍二叉树的基础,包括了概念和性质,然后再介绍如何使用二叉树,包括创建,查找等。
2.1 概念 + 性质
- 二叉树是指分叉最多为2的树,是树的一种
- 一个二叉树要么为空,要么就是根节点、右子树、左子树酌情有
- 二叉树有两种特殊的类别,分别是满二叉树和完全二叉树。其中,满二叉树是一种特殊的完全二叉树
- 满二叉树:一棵二叉树,每层都放满了
- 完全二叉树:没放满,但是是按照顺序放节点
❤️二叉树的性质
2.2 二叉树的存储
- 顺序存储
- 类似于链表的链式存储:通过一个一个的节点引用起来的,常见的表示方式有孩子表示法和孩子双亲表示法
// 孩子表示法
class Node {
int val; // 数据域
Node left; // 左孩子的引用,常常代表左孩子为根的整棵左子树
Node right; // 右孩子的引用,常常代表右孩子为根的整棵右子树
}
// 孩子双亲表示法
class Node {
int val; // 数据域
Node left; // 左孩子的引用,常常代表左孩子为根的整棵左子树
Node right; // 右孩子的引用,常常代表右孩子为根的整棵右子树
Node parent; // 当前节点的根节点
}
2.2 二叉树的基本操作
手动创建一棵二叉树
public class BinaryTree {
static class TreeNode{
private int val;
private TreeNode left;
private TreeNode right;
public TreeNode(char val){
this.val = val;
}
}
public TreeNode createTree(){
TreeNode node1 = new TreeNode('A');
TreeNode node2 = new TreeNode('B');
TreeNode node3 = new TreeNode('C');
TreeNode node4 = new TreeNode('D');
TreeNode node5 = new TreeNode('D');
TreeNode node6 = new TreeNode('D');
node1.left = node2;
node1.right = node3;
node2.left = node4;
node4.right = node5;
node3.left = node6;
return node1;
}
}
遍历:前、中、后、层序
- 前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点—>根的左子树—>根的右子树
public void preOrder1(TreeNode root){
if (root == null){
return;
}
System.out.print(root.val + " ");
preOrder1(root.left);
preOrder1(root.right);
}
//用 List 但是没有用到返回值
List<Integer> ret = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return ret;
//System.out.print(root.val+" ");
ret.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return ret;
}
//用上了返回值
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if(root == null) return ret;
ret.add(root.val);
List<Integer> leftTree = preorderTraversal(root.left);
ret.addAll(leftTree);
List<Integer> rightTree = preorderTraversal(root.right);
ret.addAll(rightTree);
return ret;
}
- 中序遍历(Inorder Traversal)——根的左子树—>根节点—>根的右子树
public void inOrder1(TreeNode root){
if (root == null){
return;
}
inOrder1(root.left);
System.out.print(root.val + " ");
inOrder1(root.right);
}
List<Character> ret = new ArrayList<>();
public List<Character> inOrder2(TreeNode root){
if (root == null){
return ret;
}
inOrder2(root.left);
ret.add(root.val);
inOrder2(root.right);
return ret;
}
public List<Character> inOrder(TreeNode root){
List<Character> ret = new ArrayList<>();
if (root == null){
return ret;
}
List<Character> leftTree = inOrder(root.left);
ret.addAll(leftTree);
ret.add(root.val);
List<Character> rightTree = inOrder(root.right);
ret.addAll(rightTree);
return ret;
}
- 后序遍历(Postorder Traversal)——根的左子树—>根的右子树—>根节点
public void postOrder1(TreeNode root){
if (root == null){
return;
}
postOrder1(root.left);
postOrder1(root.right);
System.out.print(root.val + " ");
}
List<Character> ret = new ArrayList<>();
public List<Character> postOrder2(TreeNode root){
if (root == null){
return ret;
}
postOrder2(root.left);
postOrder2(root.right);
ret.add(root.val);
return ret;
}
public List<Character> postOrder(TreeNode root){
List<Character> ret = new ArrayList<>();
if (root == null){
return ret;
}
List<Character> leftTree = postOrder(root.left);
ret.addAll(leftTree);
List<Character> rightTree = postOrder(root.right);
ret.addAll(rightTree);
ret.add(root.val);
return ret;
}
- 层序遍历
- 设二叉树的根节点所在层数为1,层序遍历就是从所在二叉树的根节点出发,首先访问第一层的树根节点,然后从左到右访问第2层上的节点,接着是第三层的节点,以此类推,自上而下,自左至右逐层访问树的结点的过程就是层序遍历
不能根据前序遍历和后续遍历创建一个二叉树,因为前序和后续确定的都是根,确定不了左和右
获取树中节点的个数
// 遍历,只要 root 不为空就可以++
public static int usedSize = 0;
public int size(TreeNode root) {
if(root == null) {
return 0;
}
usedSize++;
size(root.left);
size(root.right);
return usedSize;
}
//左树结点 + 右树结点 + 1 = 整棵树的结点
public int size2(TreeNode root) {
if(root == null) {
return 0;
}
return size2(root.left) + size2(root.right) + 1;
}
3.获取叶子节点的个数
// 遍历,只要 root 不为空就可以++
public static int leafSize = 0;
public int getLeafNodeCount(TreeNode root) {
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
leafSize++;
}
getLeafNodeCount(root.left);
getLeafNodeCount(root.right);
return leafSize;
}
//左树结点 + 右树结点 + 1 = 整棵树的结点
public int getLeafNodeCount2(TreeNode root) {
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
return 1;
}
return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
}
4.获取第K层节点的个数
public int getKLevelNodeCount(TreeNode root, int k) {
if(root == null) {
return 0;
}
if(k == 1) {
return 1;
}
return getKLevelNodeCount(root.left,k-1)
+ getKLevelNodeCount(root.right,k-1);
}
5.获取二叉树的高度
public int getHeight(TreeNode root) {
if(root == null) {
return 0;
}
int leftH = getHeight(root.left);
int rightH = getHeight(root.right);
return (leftH > rightH ? leftH :rightH) + 1;
}
public int getHeight2(TreeNode root) {
if(root == null) {
return 0;
}
return (getHeight2(root.left) > getHeight2(root.right) ?
getHeight2(root.left) :getHeight2(root.right)) + 1;
}
6.检测值为value的元素是否存在
public TreeNode find(TreeNode root,int val) {
if(root == null) return null;
if(root.val == val) {
return root;
}
TreeNode leftL = find(root.left,val);
if(leftL != null) {
return leftL;
}
TreeNode leftLR = find(root.right,val);
if(leftLR != null) {
return leftLR;
}
return null;
}
8.层序遍历
public void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
TreeNode top = queue.poll();
System.out.print(top.val+" ");
if(top.left != null) {
queue.offer(top.left);
}
if(top.right != null) {
queue.offer(top.right);
}
}
}
public List<List<Integer>> levelOrder2(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();//这一层节点的个数
List<Integer> list = new ArrayList<>();
while (size != 0) {
TreeNode top = queue.poll();
//System.out.print(top.val+" ");
list.add(top.val);
if(top.left != null) {
queue.offer(top.left);
}
if(top.right != null) {
queue.offer(top.right);
}
size--;
}
ret.add(list);
}
return ret;
}
9.判断一棵树是不是完全二叉树
public boolean isCompleteTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
if(root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if(cur != null) {
queue.offer(cur.left);
queue.offer(cur.right);
}else {
break;
}
}
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
if(cur != null) {
return false;
}
}
return true;
}
10.在root这棵树当中 找到node这个节点上的位置
public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
if(root == null) {
return false;
}
stack.push(root);
if(root == node) {
return true;
}
boolean ret = getPath(root.left,node,stack);
if(ret == true) {
return true;
}
boolean ret2 = getPath(root.right,node,stack);
if(ret2 == true) {
return true;
}
stack.pop();
return false;
}
11.求最大深度
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
int leftH = maxDepth(root.left);
int rightH = maxDepth(root.right);
if(leftH >= 0 && rightH >= 0 &&
Math.abs(leftH-rightH) <= 1) {
return Math.max(leftH,rightH) + 1;
}else {
return -1;
}
}
2.3 二叉树练习
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q != null || p != null && q == null) {
return false;
}
if(p == null && q == null) {
return true;
}
//一定是p 和 q 都不等于空!
if(p.val != q.val) {
return false;
}
return isSameTree(p.left,q.left)
&& isSameTree(p.right,q.right);
}
2.另一棵数的子树
// 时间复杂度: O(min(m,n))
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q != null || p != null && q == null) {
return false;
}
if(p == null && q == null) {
return true;
}
//一定是p 和 q 都不等于空!
if(p.val != q.val) {
return false;
}
return isSameTree(p.left,q.left)
&& isSameTree(p.right,q.right);
}
//时间复杂度:O(S*T)
//每个s 都要和 t 判断是不是相同的!
public boolean isSubtree(TreeNode root, TreeNode subRoot) {
if(root == null) {
return false;
}
if(isSameTree(root,subRoot)) {
return true;
}
if(isSubtree(root.left,subRoot)) {
return true;
}
if(isSubtree(root.right,subRoot)) {
return true;
}
return false;
}
3.翻转二叉树
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
invertTree(root.right);
return root;
}
4.是否是平衡二叉树
//时间复杂度:
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int leftHight = getHeight(root.left);
int rightHight = getHeight(root.right);
return Math.abs(leftHight-rightHight) < 2
&& isBalanced(root.left)
&& isBalanced(root.right);
}
//O(n)
public boolean isBalanced1(TreeNode root) {
if(root == null) return true;
return maxDepth(root) >= 0;
}
5.对称二叉树
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
return isSymmetricChild(root.left,root.right);
}
public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
if(leftTree == null && rightTree != null ||
leftTree != null && rightTree == null ) {
return false;
}
if(leftTree == null && rightTree == null) {
return true;
}
if(leftTree.val != rightTree.val) {
return false;
}
return isSymmetricChild(leftTree.left,rightTree.right)
&& isSymmetricChild(leftTree.right,rightTree.left);
}
public void preOrderNor(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
System.out.print(cur.val + " ");
cur = cur.left;
}
//cur == null
TreeNode top = stack.pop();
cur = top.right;
}
}
public void inOrderNor(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
//cur == null
TreeNode top = stack.pop();
System.out.print(top.val + " ");
cur = top.right;
}
}
public void postOrderNor(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
TreeNode prev= null;
while (cur != null || !stack.empty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
//cur == null
TreeNode top = stack.peek();
if(top.right == null || top.right == prev) {
System.out.print(top.val+" ");
prev = top;//记录下来当前的top已经被打印过了
stack.pop();
}else {
cur = top.right;
}
}
}
import java.util.Scanner;
class TreeNode {
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
TreeNode root = createTree(str);
inOrder(root);
}
}
public static int i = 0;
public static TreeNode createTree(String str) {
TreeNode root = null;
if(str.charAt(i) != '#') {
root = new TreeNode(str.charAt(i));
i++;
root.left = createTree(str);
root.right = createTree(str);
}else {
i++;
}
return root;
}
public static void inOrder(TreeNode root) {
if (root == null) return;
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
}
10.二叉树的最近公共祖先
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(p == root || q == root) {
return root;
}
TreeNode leftRet = lowestCommonAncestor(root.left,p,q);
TreeNode rightRet = lowestCommonAncestor(root.right,p,q);
if(leftRet != null && rightRet != null) {
return root;
}else if(leftRet != null) {
return leftRet;
}else {
return rightRet;
}
}
public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
Stack<TreeNode> s1 = new Stack<>();
getPath(root,p,s1);
Stack<TreeNode> s2 = new Stack<>();
getPath(root,q,s2);
int size1 = s1.size();
int size2 = s2.size();
if(size1 > size2) {
int size = size1 - size2;
while (size != 0) {
s1.pop();
size--;
}
}else {
int size = size2 - size1;
while (size != 0) {
s2.pop();
size--;
}
}
//两个栈当中 的元素 是一样大小的
while (!s1.empty() && !s2.empty()) {
TreeNode tmp1 = s1.pop();
TreeNode tmp2 = s2.pop();
if(tmp1 == tmp2) {
return tmp1;
}
}
return null;
}
public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
if(root == null) {
return false;
}
stack.push(root);
if(root == node) {
return true;
}
boolean ret = getPath(root.left,node,stack);
if(ret == true) {
return true;
}
boolean ret2 = getPath(root.right,node,stack);
if(ret2 == true) {
return true;
}
stack.pop();
return false;
}
11.根据二叉树创建字符串
class Solution {
public String tree2str(TreeNode root) {
if (root == null) return null;
StringBuilder StringBuilder = new StringBuilder();
tree2strChild(root, StringBuilder);
return StringBuilder.toString();
}
private void tree2strChild(TreeNode t, StringBuilder stringBuilder){
if (t == null) return;
stringBuilder.append(t.val);
if (t.left != null){
stringBuilder.append("(");
tree2strChild(t.left, stringBuilder);
stringBuilder.append(")");
}else{
if (t.right == null){
return;
}else{
stringBuilder.append("()");
}
}
if (t.right != null){
stringBuilder.append("(");
tree2strChild(t.right, stringBuilder);
stringBuilder.append(")");
}else{
return;
}
}
}