美文网首页
111. Minimum Depth of Binary Tre

111. Minimum Depth of Binary Tre

作者: 衣介书生 | 来源:发表于2018-04-05 14:51 被阅读11次

题目分析

题目链接
这道题目是求一个树的最小深度,这里使用递归的方法进行求解。

代码

/**

  • Definition for binary tree

  • public class TreeNode {

  • int val;
    
  • TreeNode left;
    
  • TreeNode right;
    
  • TreeNode(int x) { val = x; }
    
  • }
    */
    public class Solution {
    public int run(TreeNode root) {
    return minDepth(root);
    }

    public int minDepth(TreeNode root) {
    if(root == null) {
    return 0;
    }
    if(root.left == null && root.right == null) {
    return 1;
    } else if(root.left == null) {
    return 1 + minDepth(root.right);
    } else if(root.right == null) {
    return 1 + minDepth(root.left);
    } else {
    return 1 + ((minDepth(root.left) > minDepth(root.right)) ? minDepth(root.right) : minDepth(root.left));
    }
    }
    }

相关文章

网友评论

      本文标题:111. Minimum Depth of Binary Tre

      本文链接:https://www.haomeiwen.com/subject/nsjnqftx.html