Minimum Depth of Binary Tree - LeetCode

来源:互联网 发布:比特币 2013年淘宝 编辑:程序博客网 时间:2024/05/30 23:11

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int AllNode(TreeNode *node,int pathnum,int min)    {    pathnum = pathnum + 1;    if(node->left == NULL && node->right == NULL)    {    if (min == 1)    {    min = pathnum;    }    if (pathnum < min)    {    return pathnum;    }    elsereturn min;    }       if (node->left != NULL)    {    min = AllNode(node->left, pathnum, min);    }    if(node->right != NULL)    {    int x = AllNode(node->right,pathnum, min);    if (min == 1)    {    min = x;    }    else    min = min<x?min:x;    }    return min;    }    int minDepth(TreeNode *root)    {    if (root == NULL)    {    return 0;    }    else        return AllNode(root,0,1);    }};


 

0 0