• 二叉树面试题


    1、求二叉树的深度

    public class BinaryTreeTest {
    
    
        public static void main(String[] args) {
            Tree left = new Tree(1, null, null);
            Tree right = new Tree(2, null, null);
            Tree right1 = new Tree(3, left, right);
            Tree right2 = new Tree(4, null, null);
            Tree head = new Tree(5, right1, right2);
    
            //求二叉树的深度
            int depth = getDepth(head);
            System.out.println(depth);
        }
    
        public static int getDepth(Tree root) {
            if(root == null){
                return 0;
            }
            int left = getDepth(root.left);
            int right = getDepth(root.right);
            return Math.max(left, right) + 1;
        }
    
        static class Tree{
            int val;
    
            Tree left;
            Tree right;
    
            public Tree(int val, Tree left, Tree right) {
                this.val = val;
                this.left = left;
                this.right = right;
            }
        }
    }

    2、求二叉树的最小深度

    3、求二叉树的叶子节点

    public static int getNodeCount(Tree root){
            if(root == null){
                return 0;
            }
            if(root.left == null && root.right == null){
                return 1;
            }
            int left = getNodeCount(root.left);
            int right = getNodeCount(root.right);
            return left + right;
        }

    4、5、6 三种遍历二叉树的算法(前、中、后):针对的是根节点的位置

    前序遍历

     public static List<Integer> getPrev(Tree root) {
            List<Integer> nodes = new ArrayList<>();
            return getNodes(root, nodes);
        }
    
        private static List<Integer> getNodes(Tree root, List<Integer> nodes) {
            if(root == null){
                return nodes;
            }
            nodes.add(root.val);
            getNodes(root.left, nodes);
            getNodes(root.right, nodes);
            return nodes;
        }

    中序遍历

     public static List<Integer> getPrev(Tree root) {
            List<Integer> nodes = new ArrayList<>();
            return getNodes(root, nodes);
        }
    
        private static List<Integer> getNodes(Tree root, List<Integer> nodes) {
            if(root == null){
                return nodes;
            }
            getNodes(root.left, nodes);
            nodes.add(root.val);
            getNodes(root.right, nodes);
            return nodes;
        }

    后序遍历

  • 相关阅读:
    laravel获取不到session
    laravel表单提交419错误
    'cross-env' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
    centos 虚拟机出问题 Oh no,something has gone wrong! 解决方法
    fastadmin关闭验证码登录
    php二维数组排序
    不自动显示html表单记住的内容 自动完成等清除记忆
    两个服务器之间使用minio同步文件
    redis获取数据库个数
    html跳转页面
  • 原文地址:https://www.cnblogs.com/zhangchiblog/p/12044603.html
Copyright © 2020-2023  润新知