111. Minimum Depth of Binary Tree

来源:互联网 发布:excel数据透视表分析 编辑:程序博客网 时间:2024/05/29 09:43

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 a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int depth = 1e8;    int minDepth(TreeNode* root) {               if(root == NULL) return 0;        DFS(root);        return depth;    }    int d = 0;    void DFS(TreeNode* root) {        d++;        if(root->left == NULL && root->right == NULL)        {            if(d < depth)                depth = d;            return;        }        if(root->left)        {            DFS(root->left);            d--;        }        if(root->right)        {            DFS(root->right);            d--;        }            }};


原创粉丝点击