Leetcode--Minimum Depth of Binary Tree

来源:互联网 发布:php调用python 编辑:程序博客网 时间:2024/06/11 04:37

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.

Hide Tags
 Tree Depth-first Search
Have you been asked this question in an interview? 

思路:记忆深搜获取所有叶子节点的深度,保存到vector中。再将容器的元素排序,结果返回第一个元素


/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    vector<int> res;    void function(TreeNode *root,int num)    {        if(root==NULL)            res.push_back(num);        else{            int temp=num+1;            if(root->left==NULL&&root->right==NULL)                function(root->left,temp);            else if(root->left!=NULL&&root->right==NULL)                function(root->left,temp);            else if(root->left==NULL&&root->right!=NULL)                function(root->right,temp);            else{                function(root->left,temp);                function(root->right,temp);            }        }    }    int minDepth(TreeNode *root) {        if(root==NULL)              return 0;        function(root,0);        sort(res.begin(),res.end());        return res[0];    }};


0 0
原创粉丝点击