剑指offer-39.二叉树的深度

来源:互联网 发布:激光洗眉机网络假货 编辑:程序博客网 时间:2024/06/03 15:53
    /**     * 求二叉树的深度     * 递归:二叉树的深度等于左右子树的深度的最大值+1     * 参考后序遍历     */    public int treeDepth(TreeNode root) {        if(root == null)            return 0;        int leftDepth = treeDepth(root.left);        int rightDepth = treeDepth(root.right);        return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1;    } 
    /**     * 记录二叉树中每条路径     * 思路:仿照前序遍历     * @param args     */      public void getAllPaths(TreeNode root){            if(root == null)                return;            path.add(root.val);            if(root.left == null && root.right == null){                result.add(new ArrayList<>(path));            }            getAllPaths(root.left);            getAllPaths(root.right);            path.remove(path.size()-1);    }