[leetcode刷题系列]Minimum Depth of Binary Tree

来源:互联网 发布:mac 免费uml建模工具 编辑:程序博客网 时间:2024/05/19 13:44

- - 不说了

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {    void dfs(TreeNode * root, int now, int & ans){        if(root->left == 0 && root->right == 0){            if(ans == -1 || now < ans)                ans = now;            return ;        }        if(root->left != 0)            dfs(root->left, now + 1, ans);        if(root->right != 0)            dfs(root->right, now + 1, ans);    }public:    int minDepth(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == 0)            return 0;        int ans = -1;        dfs(root, 1, ans);        return ans;    }};


原创粉丝点击