篇章八 数据结构——二叉树

目录

1.树型结构

1.1 概念

1.2 树内部概念

1.3 树的表示形式

1.4 树的应用

2. 二叉树

2.1 概念

​编辑

2.2 两种特殊的二叉树

2.3 二叉树的性质

2.4 二叉树的基本操作

1.前序遍历:

2.中序遍历

3.后序遍历 

4.获取叶子节点的个数

5.获取第K层节点的个数

6.获取二叉树的高度

7.检测值为value的元素是否存在

8.层序遍历

9.判断一棵树是不是完全二叉树

2.5 二叉树相关oj题

1.检查两颗树是否相同

2.判断是不是另一颗树的子树

3.翻转二叉树

4.对称二叉树

5.判断一颗二叉树是否是平衡二叉树

6.二叉树的构建及遍历

7.二叉树的分层遍历

8.给定一个二叉树, 找到该树中两个指定节点的最近公共祖先

9.根据一棵树的前序遍历与中序遍历构造二叉树

10.根据一棵树的中序遍历与后序遍历构造二叉树

11.二叉树创建字符串

12.二叉树前序非递归遍历实现

13.二叉树中序非递归遍历实现

14.二叉树后序非递归遍历实现

15.二叉搜索树与双向链表


1.树型结构

1.1 概念

        树是一种非线性的数据结构,它是由n(n>=0)个有限结点组成一个具有层次关系的集合。把它叫做树是因为它看起来像一棵倒挂的树,也就是说它是根朝上,而叶朝下的。它具有以下的特点:

  • 有一个特殊的结点,称为根结点,根结点没有前驱结点

  • 除根结点外,其余结点被分成M(M > 0)个互不相交的集合T1、T2、......、Tm,其中每一个集合Ti (1 <= i <=m) 又是一棵与树类似的子树。每棵子树的根结点有且只有一个前驱,可以有0个或多个后继

  • 树是递归定义的。

 

注意:

        树形结构中,子树之间不能有交集,否则就不是树形结构

如下图:

1.2 树内部概念

结点的度:一个结点含有子树的个数称为该结点的度; 如上图:A的度为6

树的度:一棵树中,所有结点度的最大值称为树的度; 如上图:树的度为6

叶子结点或终端结点:度为0的结点称为叶结点; 如上图:B、C、H、I...等节点为叶结点

双亲结点或父结点:若一个结点含有子结点,则这个结点称为其子结点的父结点; 如上图:A是B的父结点

孩子结点或子结点:一个结点含有的子树的根结点称为该结点的子结点; 如上图:B是A的孩子结点

根结点:一棵树中,没有双亲结点的结点;如上图:A结点的层次:从根开始定义起,根为第1层,根的子结点为第2层,以此类推

树的高度或深度:树中结点的最大层次; 如上图:树的高度为4

非终端结点或分支结点:度不为0的结点; 如上图:D、E、F、G...等节点为分支结点

兄弟结点:具有相同父结点的结点互称为兄弟结点; 如上图:B、C是兄弟结点

堂兄弟结点:双亲在同一层的结点互为堂兄弟;如上图:H、I互为兄弟结点

结点的祖先:从根到该结点所经分支上的所有结点;如上图:A是所有结点的祖先

子孙:以某结点为根的子树中任一结点都称为该结点的子孙。如上图:所有结点都是A的子孙

森林:由m(m>=0)棵互不相交的树组成的集合称为森林

1.3 树的表示形式

        树结构相对线性表就比较复杂了,要存储表示起来就比较麻烦了,实际中树有很多种表示方式,如:双亲表示法,孩子表示法、孩子双亲表示法、孩子兄弟表示法等等。我们这里就简单的了解其中最常用的孩子兄弟表示法。

class Node {
   int value;
// 树中存储的数据
   Node firstChild;
// 第一个孩子引用
   Node nextBrother;
// 下一个兄弟引用
}

1.4 树的应用

文件系统管理(目录和文件)

2. 二叉树

2.1 概念

一棵二叉树是结点的一个有限集合,该集合:

  1. 或者为空

  2. 或者是由一个根节点加上两棵别称为左子树和右子树的二叉树组成。

从上图可以看出:

  1. 二叉树不存在度大于2的结点

  2. 二叉树的子树有左右之分,次序不能颠倒,因此二叉树是有序树

注意:对于任意的二叉树都是由以下几种情况复合而成的:  

2.2 两种特殊的二叉树

  1. 满二叉树: 一棵二叉树,如果每层的结点数都达到最大值,则这棵二叉树就是满二叉树。也就是说,如果一棵二叉树的层数为K,且结点总数是,则它就是满二叉树。

  2. 完全二叉树: 完全二叉树是效率很高的数据结构,完全二叉树是由满二叉树而引出来的。对于深度为K的,有n个结点的二叉树,当且仅当其每一个结点都与深度为K的满二叉树中编号从0至n-1的结点一一对应时称之为完全二叉树。 要注意的是满二叉树是一种特殊的完全二叉树。

注意:

        非完全二叉树(如下图):

2.3 二叉树的性质

1.若规定根结点的层数为1,则一棵非空二叉树的第i层上最多有2^{i-1}(i>0)个结点

2.若规定只有根结点的二叉树的深度为1,则深度为K的二叉树的最大结点数是2^{k} - 1(k>=0)

3.对任何一棵二叉树, 如果其叶结点个数为 n0, 度为2的非叶结点个数为 n2,则有n0=n2+1

4.具有n个结点的完全二叉树的深度k为\log_2 (n + 1)向上取整

5.对于具有n个结点的完全二叉树,如果按照从上至下从左至右的顺序对所有节点从0开始编号,则对于序号为i的结点有:

  • 若i>0,双亲序号:(i-1)/2;i=0,i为根结点编号,无双亲结点

  • 若2i+1<n,左孩子序号:2i+1,否则无左孩子

  • 若2i+2<n,右孩子序号:2i+2,否则无右孩子

6.练习

1)某二叉树共有 399 个结点,其中有 199 个度为 2 的结点,则该二叉树中的叶子结点数为( )
A 不存在这样的二叉树
B 200 √
C 198
D 199

2)在具有 2n 个结点的完全二叉树中,叶子结点个数为( )
A n √
B n+1
C n-1
D n/2

3)一个具有767个节点的完全二叉树,其叶子节点个数为()
A 383√
B 384
C 385
D 386

4) 一棵完全二叉树的节点数为531个,那么这棵树的高度为( )
A 11
B 10√
C 8
D 12

2.4 二叉树的基本操作

1.前序遍历:

public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

2.中序遍历

public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

3.后序遍历 

public void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }

        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

4.获取叶子节点的个数

1)遍历方案: 

public static int leafNodeCount = 0;
    public void getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafNodeCount++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

 2)子问题方案

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);
    }

5.获取第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);
    }

6.获取二叉树的高度

public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;

}

7.检测值为value的元素是否存在

    public TreeNode find(TreeNode root, int val) {
        if(root == null) {
            return null;
        }
        if(root.val == val) {
            return root;
        }
        TreeNode leftT = find(root.left, val);
        if (leftT.val == val) {
            return leftT;
        }

        TreeNode rightT = find(root.right, val);
        if (rightT.val == val) {
            return rightT;
        }
        return null;
    }

8.层序遍历

class Solution {
    public void levelOrder(TreeNode root) {
        if(root == null) {
            return;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = null;
        queue.offer(root);

        while(!queue.isEmpty()) {
                cur = queue.poll();
                System.out.print(cur.val + " ");

                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
               
            }
           
        }
       
    }
}
此处用到了队列来辅助完成层序遍历

9.判断一棵树是不是完全二叉树

public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        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()) {

            if (queue.poll() != null) {
                return false;
            }
        }

        return true;
    }

2.5 二叉树相关oj题

1.检查两颗树是否相同

OJ链接

class Solution {
    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;
        }

        if(p.val != q.val) {
            return false;
        }

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

注意时间复杂度:        

2.判断是不是另一颗树的子树

OJ链接

class Solution {
    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;
    }

    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;
        }

        if(p.val != q.val) {
            return false;
        }

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

3.翻转二叉树

OJ链接

class Solution {
    public static TreeNode tmp;
    public TreeNode invertTree(TreeNode root) {
        if(root == null) {
            return null;
        }
		if(root.left == null && root.right == null)
		{
			return root;
		}

        tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);
        return root;        
    }
}

4.对称二叉树

class Solution {
    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) ;

         
    }
}

5.判断一颗二叉树是否是平衡二叉树

OJ链接

 1)时间复杂度 O(n^2) 

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        
        return Math.abs(getHeight(root.left) - getHeight(root.right)) < 2 && isBalanced(root.left) && isBalanced(root.right);
    }

    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }
}

2)时间复杂度 O(n)

class Solution {
    public boolean isBalanced(TreeNode root) {
        if(root == null) { 
            return true;
        }
        
        return getHeight(root) >= 0;
    }

    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int leftHeight = getHeight(root.left);
        if(leftHeight < 0) {
            return -1;
        }
        
        int rightHeight = getHeight(root.right);
        if(rightHeight < 0) {
            return -1;
        }
        
        if(Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        }else {
            return -1;
        }
    }
}

6.二叉树的构建及遍历

OJ链接

import java.util.Scanner;

class TreeNode {
    public char val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(char val) {
        this.val = val;
    }
}

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);
            inorderTree(root);
        }
    }

    public int i = 0;
    public 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 void inorderTree(TreeNode root) {
        if(root == null) {
            return;
        }
        inorderTree(root.left);
        System.out.print(root.val + " ");
        inorderTree(root.right);

    }

}

7.二叉树的分层遍历

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = null;
        queue.offer(root);

        while(!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while(size != 0) {
                cur = queue.poll();
                list.add(cur.val);

                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;
            }
            ret.add(list); 
        }
        return ret;
    }
}

8.给定一个二叉树, 找到该树中两个指定节点的最近公共祖先

OJ链接

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) {
            return null;
        }

        if(root == p || root == q) {
            return root;
        }

        TreeNode leftTree = lowestCommonAncestor(root.left, p, q);
        TreeNode rightTree = lowestCommonAncestor(root.right, p, q);

        if(leftTree != null && rightTree != null) {
            return root;
        }else if(leftTree != null) {
            return leftTree;
        }else {
            return rightTree;
        }
    }
}

9.根据一棵树的前序遍历与中序遍历构造二叉树

OJ链接

class Solution {
    public int preIndex;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin ,int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findVal(inorder, inbegin, inend, preorder[preIndex]);

        preIndex++;

        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex - 1);
        root.right = buildTreeChild(preorder, inorder, rootIndex + 1, inend);

        return root;
    }

    private int findVal(int[] inorder, int inbegin, int inend, int val) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}

10.根据一棵树的中序遍历与后序遍历构造二叉树

class Solution {
    public int postIndex;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    	postIndex = postorder.length - 1;	
        return buildTreeChild(inorder,postorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(int[] inorder, int[] postorder, int inbegin ,int inend) {
        if(inbegin > inend) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postIndex]);

        int rootIndex = findVal(inorder, inbegin, inend, postorder[postIndex]);

        postIndex--;

		root.right = buildTreeChild(inorder, postorder, rootIndex + 1, inend);
        root.left = buildTreeChild(inorder, postorder, inbegin, rootIndex - 1);
        

        return root;
    }

    private int findVal(int[] inorder, int inbegin, int inend, int val) {
        for(int i = inbegin; i <= inend; i++) {
            if(inorder[i] == val) {
                return i;
            }
        }
        return -1;
    }
}

11.二叉树创建字符串

OJ链接

class Solution {
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();

        tree2strChild(root, stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2strChild(TreeNode root, StringBuilder stringBuilder) {
        if(root == null) {
            return;
        }

        stringBuilder.append(root.val);

        if(root.left != null) {
            stringBuilder.append("(");
            tree2strChild(root.left, stringBuilder);
            stringBuilder.append(")");
        }else {
            if(root.right == null) {
                return;
            }else {
                stringBuilder.append("()");
            }
        }

        if(root.right != null) {
            stringBuilder.append("(");
            tree2strChild(root.right, stringBuilder);
            stringBuilder.append(")");
        }else {
            return;
        }
    }
}

12.二叉树前序非递归遍历实现

OJ链接

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
       List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()){
            while(cur != null) {
                stack.push(cur);
                list.add(cur.val);

                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        } 
        return list;
    }
}

13.二叉树中序非递归遍历实现

OJ链接

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;

        while(cur != null || !stack.isEmpty()){
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        } 
        return list;
    }
}

14.二叉树后序非递归遍历实现

OJ链接

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        
        Stack<TreeNode> stack = new Stack();
        TreeNode cur = root;
        TreeNode prev = null;

        while(cur != null || !stack.isEmpty()){
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev) {
                list.add(top.val);
                stack.pop();
                prev = top;
            }else {
                cur = top.right;
            }
        } 
        return list;
    }
} 

15.二叉搜索树与双向链表

OJ链接

import java.util.*;
public class Solution {
    TreeNode prev = null;
    public void ConvertChild(TreeNode root) {
        if(root == null) {
            return;
        }

        ConvertChild(root.left);

        // 打印
        root.left = prev;    
        if(prev != null) {
            prev.right = root;
        }
        prev = root;

        ConvertChild(root.right);
    }

    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null) {
            return null;
        }

        ConvertChild(pRootOfTree);

        while(pRootOfTree.left != null) {
            pRootOfTree = pRootOfTree.left;
        }

        return pRootOfTree;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值