二叉树面试题

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

后序遍历

原文地址:https://www.cnblogs.com/zhangchiblog/p/12044603.html