求二叉树的最短路径。 做法就是遍历所有分支找到最短的路径即可。 终止条件是找到叶子节点即左右子节点都是null。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int res = 999999;
public int minDepth(TreeNode root) {
if( root == null )
{
return 0;
}
fun( root,1);
return res;
}
void fun(TreeNode root , int dep)
{
if( root.left == null && root.right == null )
{
if( dep < res )
{
res = dep;
}
}
if( root.left != null )
{
fun( root.left,dep+1);
}
if( root.right != null )
{
fun( root.right,dep+1);
}
}
}