Tree some functions

树的总结点数
递归post-order dfs来upwards累积

private int countAllNodes(TreeNode root) { 
        if(root == null) return 0;
        return 1 + countAllNodes(root.left) + countAllNodes(root.right);
    }

树的最大深度
递归post-order dfs来upwards累积

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

树的最小深度
递归post-order dfs来upwards累积

private int getMinDepth(TreeNode root) {
        if(root == null) return 0;
        int left = getMinDepth(root.left);
        int right = getMinDepth(root.right);
        return (left == 0 || right == 0) ? left + right + 1: Math.min(left,right) + 1;
    }

你可能感兴趣的:(Tree some functions)