zoukankan      html  css  js  c++  java
  • 二叉树面试题

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

    后序遍历

  • 相关阅读:
    常见的分布
    ubuntu16.04获取root权限并用root用户登录
    神经网络与深度学习邱锡鹏学习笔记16多项式回归
    什么是公版显卡,什么是非公版显卡
    高考电子监控揭秘
    买了个2手睡袋
    HTML
    又是一天
    我也想去看珠峰
    Qt 主界面菜单栏和状态栏实现
  • 原文地址:https://www.cnblogs.com/zhangchiblog/p/12044603.html
Copyright © 2011-2022 走看看