111.二叉树的最小深度

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

111.二叉树的最小深度1

返回它的最小深度 2

 

 遍历的顺序为后序(左右中),可以看出:求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。

public int minDepth(TreeNode root) {
        return process(root);
    }
    private int process(TreeNode node){
        if(node==null){
            return 0;
        }
        int leftDepth=process(node.left);
        int rightDepth=process(node.right);
        if(node.left==null && node.right!=null){
            return rightDepth+1;
        }
        if(node.right==null && node.left!=null){
            return leftDepth+1;
        }
      
        return Math.min(leftDepth,rightDepth)+1;  
    }

  

 public int minDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        return process(root);
    }
    private int process(TreeNode node){
        if(node.left==null && node.right==null){
            return 1;
        }
        int lH=Integer.MAX_VALUE;
        if(node.left!=null){
            lH=process(node.left);
        }
        int rH=Integer.MAX_VALUE;
        if(node.right!=null){
            rH=process(node.right);
        }
        return Math.min(lH,rH)+1;
    }

  

  

104.二叉树的最大深度

public int maxDepth(TreeNode root) {
        return process(root);

    }

    private int process(TreeNode node){
        if(node==null){
            return 0;
        }
        int leftDepth=process(node.left);
        int rightDepth=process(node.right);
        if(node.left!=null && node.right==null){
            return leftDepth+1;
        }
        if(node.right!=null && node.left==null){
            return rightDepth+1;
        }
        return Math.max(leftDepth,rightDepth)+1;
    }

  

 

222.完全二叉树的节点个数

给出一个完全二叉树,求出该树的节点个数。

示例 1:

  • 输入:root = [1,2,3,4,5,6]
  • 输出:6
 public int countNodes(TreeNode root) {
        return process(root);
    }

    //left.nodes right.nodes l+r +1
    private int process(TreeNode root){
        if(root==null){
            return 0;
        }
        int leftNodes=process(root.left);
        int rightNodes=process(root.right);
        return leftNodes+rightNodes+1;
    }

  

posted @ 2021-10-05 23:51  sherry001  阅读(54)  评论(0编辑  收藏  举报