Minimum Depth of Binary Tree LeetCode

来源:互联网 发布:诺维斯基10年数据 编辑:程序博客网 时间:2024/06/07 07:09

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int minDepth(TreeNode root) {    if(root==null)return 0;    else if(root.left==null||root.right==null)    return 1+Math.max(minDepth(root.left), minDepth(root.right));    return 1+Math.min(minDepth(root.left), minDepth(root.right));    }}

递归思想要把一个问题分解成几个小问题的形式。在这个题目中,最短路径分为两种情况:

其一是该节点的左右子节点其中之一为空,此时以该节点为根的子树的最短路径为不为空的那个字结点为根的树的最短路径加一;

其二是两个子节点都不为空,此时此时以该节点为根的子树的最短路径为该节点两个子节点为根节点的树的最短路径的较小者加一。


0 0