[leetcode] Minimum Depth of Binary Tree

来源:互联网 发布:网络直播傅园慧 编辑:程序博客网 时间:2024/06/07 08:00

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.

思路:dfs

代码:

/** * 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 minDepth(TreeNode *root) {        int mindepth;        mindepth=100000;        if(root==NULL) return 0;        dfs(root,1,mindepth);        return mindepth;    }    void dfs(TreeNode *root, int depth, int &mindepth){        if(root==NULL) return;        if(root->left==NULL && root->right==NULL){            if(depth<mindepth) mindepth=depth;            return;        }        depth++;        dfs(root->left,depth,mindepth);        dfs(root->right,depth,mindepth);    }};


0 0
原创粉丝点击