Minimum Depth of Binary Tree

来源:互联网 发布:mac原唱变伴奏 编辑:程序博客网 时间:2024/05/21 19:27

【题目描述】

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.

【思路】

一般这样的题目既可以用递归的方法也可以用非递归迭代的方法做。我是用递归的方法做的,思路基本和Maximum Depth of Binary Tree的类似。

【代码】

递归:

/** * 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 minDepth(TreeNode* root) {        if(root==NULL) return 0;        if(!root->left&&!root->right) return 1;        if(root->left==NULL) return minDepth(root->right)+1;        else if(root->right==NULL) return minDepth(root->left)+1;        return min(minDepth(root->right),minDepth(root->left))+1;    }};


迭代:

//参考了soulmachine的思路

//pair是一种模板类型,包含两个数据值,两个数据的类型可以不同,pair<typename1,typename2> a,访问的话用a.first,a.second访问

//make_pair函数,自动生成pair对象

/** * 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 minDepth(TreeNode* root) {        if(root==NULL) return 0;        int result=INT_MAX;        stack<pair<TreeNode*,int>> s;        s.push(make_pair(root,1));        while(!s.empty()){            TreeNode* node=s.top().first ;            int val=s.top().second ;            s.pop();            if(node->left==NULL&&node->right==NULL) result=min(result,val);            if(node->left&&result>val) s.push(make_pair(node->left,val+1));            if(node->right&&result>val) s.push(make_pair(node->right,val+1));        }        return result;    }};


0 0
原创粉丝点击