数据结构【二叉树高频笔试题】

[FKDWSJFS](HTTP//:WWW.MFKD .GS)

二叉树01-02

n0(叶子节点) = n2(度为2的节点)+1
import java.util.LinkedList;
import java.util.Queue;
/**
 * Created with IntelliJ IDEA.
 * User: 12629
 * Date: 2022/1/17
 * Time: 8:28
 * Description:
 */
public class Test {

    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree();
        TreeNode root = binaryTree.createTree();
        binaryTree.preOrder(root);
        System.out.println();
        binaryTree.inOrder(root);
        System.out.println();
        binaryTree.postOrder(root);
        System.out.println();
        System.out.println(binaryTree.size1(root));
        System.out.println(binaryTree.size(root));
        System.out.println("=========叶子节点的个数===========");
        binaryTree.getLeafNodeCount(root);
        System.out.println(BinaryTree.leafCount);
        System.out.println("============叶子节点个数===========");
        System.out.println(binaryTree.getKLevelNodeCount(root,1));
        System.out.println("==============树的高度======");
        System.out.println(binaryTree.getHeight(root));
        System.out.println("=====查找节点=======");
        try {
            TreeNode ret = binaryTree.find(root,'E');
            System.out.println(ret.val);
        }catch (NullPointerException e) {
            e.printStackTrace();
            System.out.println("没有这个节点!");
        }
        System.out.println("============是否是完全二叉树==============");
        System.out.println(binaryTree.isCompleteTree(root));


       /* Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(null);
        queue.offer(null);
        queue.offer(null);
        queue.offer(null);
        System.out.println(queue.size());*/
    }
}
import org.omg.CORBA.PUBLIC_MEMBER;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class TreeNode {
    public char val;
    public TreeNode left;//左孩子的引用
    public TreeNode right;//右孩子的引用
    public TreeNode(char val) {
        this.val = val;
    }
}

public class BinaryTree  {

    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        System.out.print(root.val+" ");
        preOrder(root.left);
        preOrder(root.right);
    }
    
      // 中序遍历
    public  void inOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val+" ");
        inOrder(root.right);
    }
    
     // 后序遍历
    public void postOrder(TreeNode root) {
        if(root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val+" ");
    }
    //shift+f6->回车才会生效

    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> retlist = new ArrayList<>();
        if(root == null) {
            return retlist;
        }
        retlist.add(root.val);
        List<Character> leftTree = preorderTraversal(root.left);
        retlist.addAll(leftTree);

        List<Character> rightTree =preorderTraversal(root.right);
        retlist.addAll(rightTree);

        return retlist;
    }

    /*public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> retlist = new ArrayList<>();
        if(root == null) {
            return retlist;
        }
        List<Integer> leftTree = inorderTraversal(root.left);
        retlist.addAll(leftTree);

        retlist.add(root.val);


        List<Integer> rightTree =inorderTraversal(root.right);
        retlist.addAll(rightTree);

        return retlist;
    }*/

    //树的节点的个数
    int count = 0;
    public int size(TreeNode root){
        if (root == null) {
            return 0;
        }
        count++;
        size(root.left);
        size(root.right);
        return count;
    }

    public int size1(TreeNode root){
        if (root == null) {
            return 0;
        }
        return size(root.left)+size(root.right)+1;
    }

    /**
     * 获取叶子节点的个数
     * 遍历思路:
     */
    static int leafCount = 0;
    public void getLeafNodeCount(TreeNode root){
        if (root == null) {
            return 0;
        }
        if(root.left == null && root.right == null){
            leafCount++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    /**
     * 获取叶子节点的个数
     * 子问题思路
     * @param root
     * @return
     */
    public int getLeafNodeCount1(TreeNode root){
        if (root == null) {
            return 0;
        }
        if(root.left == null && root.right == null){
            //当前的root是叶子节点
            return 1;
        }
        return getLeafNodeCount1(root.left) + getLeafNodeCount1(root.right);
    }

    /**
     * 获取第K层节点的个数
     * 子问题思路:
     *
     */
    public int getKLevelNodeCount(TreeNode root,int k) {
        if (root == null || k<= 0) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left,k-1)+getKLevelNodeCount(root.right,k-1);
    }

    /**
     * 获取二叉树的高度
     * 时间复杂度:O(n)
     * 空间复杂度:O()
     */
    public int getHeight(TreeNode root){
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return leftHeight > rightHeight ? leftHeight+1 :rightHeight+1;
        //return Math.max(getHeight(root.left),getHeight(root.right))+1;
    }
    /**
     * 检测值为value的元素是否存在
     */
    TreeNode find(TreeNode root, char val) {
        if(root == null) return null;
        if(root.val == val) return root;


        TreeNode ret = find(root.left,val);
        if(ret != null) {
            return ret;
        }
        ret = find(root.right,val);
        if(ret != null) {
            return ret;
        }
        return null;
    }
    /**
     * 是不是完全二叉树
     * @param root
     * @return
     */
    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()){
            TreeNode top = queue.peek();
            if (top != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }

    /*public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> retlist = new ArrayList<>();
        if(root == null) {
            return retlist;
        }
        List<Integer> leftTree = postorderTraversal(root.left);
        retlist.addAll(leftTree);



        List<Integer> rightTree =postorderTraversal(root.right);
        retlist.addAll(rightTree);


        retlist.add(root.val);


        return retlist;
    }*/

}
/**
 * Created with IntelliJ IDEA.
 * User: 12629
 * Date: 2022/1/17
 * Time: 8:28
 * Description:
 */

二叉树02

检查两颗树是否相同 https://leetcode-cn.com/problems/same-tree/

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(q.left,p.left) && isSameTree(q.left,q.right);
    }

另一颗树的子树 https://leetcode-cn.com/problems/subtree-of-another-tree/

//判两棵树是否i相同
    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);
    }

    //另一棵树的子树
    public boolean isSubtree(TreeNode root, TreeNode subRoot){
        if(root == null || subRoot == null){
            return false;
        }
        //根节点和subRoot是不是两颗相同的树
        if (isSameTree(root, subRoot)) {
            return true;
        }
        //subRoot是不是root的左子树
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        //subRoot是不是root的右子树
        if (isSubtree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

判断一颗二叉树是否是平衡二叉树 https://leetcode-cn.com/problems/balanced-binary-tree/

//求左树和树的高度,时间复杂度:O(n);
    public int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = height(root.left);
        int righttHeight = height(root.right);
        return (leftHeight > righttHeight) ? (leftHeight + 1) : (righttHeight + 1);
    }

    //判断是不是平衡二叉树,书记兼复杂度:O(n^2);
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int left = height(root.left);
        int right = height(root.right);
        return Math.abs(left-right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }

    //求左树和树的高度,时间复杂度:O(n);
    public int height2(TreeNode root) {
        if(root == null) {return 0;}
        int leftHeight = height2(root.left);
        int righttHeight = height2(root.right);

        if(leftHeight >= 0 && righttHeight >= 0 && Math.abs(leftHeight-righttHeight) <= 1){
            return Math.max(leftHeight,righttHeight)+1;
        }else{
            //说明不平衡
            return -1;
        }
    }
//时间复杂度O(n)
    public boolean isBalanced2(TreeNode root) {
        if(root == null)  return true;
        return height2(root) >= 0;
    }

判断是不是对称二叉树https://leetcode-cn.com/problems/symmetric-tree/

 public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree){
        if(leftTree == null && rightTree != null) return false;
        if(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 boolean isSymmetric(TreeNode root) {
        i
    }

二叉树遍历https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f79btSxw-1660701594371)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1643174270287.png)]

import java.util.Scanner;
class TreeNode1{
    public char val;
    public TreeNode1 left;
    public TreeNode1 right;

    public TreeNode1(char val){
        this.val = val;
    }
}
public class Main{
    public static int i = 0;
    public static TreeNode1 creatTree(String str){
        TreeNode1 root = null;
        if(str.charAt(i) != '#'){
            root = new TreeNode1(str.charAt(i));
            i++;
            root.left= creatTree(str);
            root.right= creatTree(str);
        }else{
            i++;
        }
        return root;
    }
    public static void inorder(TreeNode1 root){
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.val+" ");
        inorder(root.right);
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()){
            String str = in.nextLine();
            TreeNode1 root = creatTree(str);
            inorder(root);
        }
    }
}

二叉树的分层遍历(层序遍历) https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

public void levelOrder(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();
        if(root == null) return;
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.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 cur = queue.poll();
                 //list.add(cur.val); //Oj上要放开注释;
                 if (cur.left != null) {
                     queue.offer(cur.left);
                 }
                 if (cur.right != null) {
                     queue.offer(cur.right);
                 }
                 size--;
             }
             ret.add(list);
         }
         return ret;
     }

二叉树03

二叉树的最近公共祖先 https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GveULd7i-1660701703576)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1644393501978.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-h9vyLyi5-1660701656064)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1644393536786.png)]

/**
     * 最近公共祖先
     * 思路一
     */
    public TreeNode lOwestCommonAncestor(TreeNode root,TreeNode p,TreeNode q){
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode leftT = lOwestCommonAncestor(root.left,p,q);
        TreeNode rightT = lOwestCommonAncestor(root.right,p,q);
        if (leftT != null && rightT != null) {
            return root;
        } else if (leftT != null) {
            return leftT;
        }else{
            return rightT;
        }
    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C0SxjZbw-1660701656065)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1644394758697.png)]

/**
     * 最近公共祖先
     * 思路二
     */
     // root:根节点     node:指定的节点        stack:存放根节点到指定节点的路径
    public boolean getPath(TreeNode root,TreeNode node,Stack<TreeNode> stack){
        if(root == null || node == null) return false;
        stack.push(root);
        if(root == node) return true;
        boolean flag = getPath(root.left,node,stack);
        if (flag) {
            return true;
        }
        flag = getPath(root.right,node,stack);
        if (flag) {
            return true;
        }
        stack.pop();
        return false;
    }

    public TreeNode lOwestCommonAncestor1(TreeNode root,TreeNode p,TreeNode q){
        if(root == null)  return null;
        Stack<TreeNode> stack1 = new Stack<>();
        getPath(root,p,stack1);
        Stack<TreeNode> stack2 = new Stack<>();
        getPath(root,q,stack2);
        int size1 = stack1.size();
        int size2 = stack2.size();
        if (size1 > size2) {
            int size = size1 - size2;
            while (size != 0) {
                stack1.pop();
                size--;
            }
            while(!stack1.isEmpty() && !stack2.isEmpty()){
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
        }else{
            int size = size2 - size1;
            while (size != 0) {
                stack1.pop();
                size--;
            }
            while(!stack1.isEmpty() && !stack2.isEmpty()){
                if (stack1.peek() == stack2.peek()) {
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
        }
        return null;
    }

二叉树搜索树转换成排序双向链表 https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-II2ROyZb-1660701656065)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1644395602024.png)]

    //二叉搜索树转换为排序的双向链表
    TreeNode prev = null;
    public void inorder(TreeNode pCur){
        if(pCur == null) return;
        inorder(pCur.left);
        //打印
        pCur.left = prev;
        if (prev != null) {
            prev.right = pCur;
        }
        prev = pCur;
        inorder(pCur.right);
    }


    public TreeNode Covert(TreeNode pRootOfTree){
        if(pRootOfTree == null) return null;
        inorder(pRootOfTree);
        TreeNode head = pRootOfTree;
        while (head.left != null) {
            head = head.left;
        }
        return head;
    }

从前序与中序遍历序列构造二叉树
从中序与后序遍历序列构造二叉树
根据二叉树创建字符串
public void treeToString(TreeNode t,StringBuilder sb){
        if(t == null) return;
        sb.append(t.val);
        if (t.left != null) {
            sb.append("(");
            treeToString(t.left,sb);
            sb.append(")");
        }else{
            //t.left == null
            if (t.right == null) {
                return;
            }else{
                sb.append("()");
            }
        }
        if(t.right == null){
            return;
        }else{
            sb.append("(");
            treeToString(t.right,sb);
            sb.append(")");
        }
    }

    public String tree2str(TreeNode root){
        if(root == null) return null;
        StringBuilder sb = new StringBuilder();
        treeToString(root,sb);
        return sb.toString();
    }
}

二叉树04

二叉树的非递归前序遍历

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Etvl1piN-1660701732449)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\1644639857784.png)]

 public List<Integer> preoderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                //System.out.println(cur.val+" ");
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }

二叉树的前序遍历
 public List<Integer> inoderTraversal(TreeNode root){
        List<Integer> ret = new ArrayList<>();
        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();
            //System.out.println(cur.val+" ");
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }

二叉树的后序遍历
 public List<Integer> postoderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        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) {
                stack.pop();
                //System.out.println(cur.val+" ");
                ret.add(top.val);
                prev = top;//记录一下最近一次打印的节点
            } else {
                cur = top.right;
            }
        }
        return ret;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值