[LeetCode]Minimum Depth of Binary Tree

来源:互联网 发布:nginx echo模块 编辑:程序博客网 时间:2024/05/01 18:32
struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {//find the minimum step of a tree, bfs works at most timepublic:int BFS(TreeNode* root){if(!root) return 0;        queue<pair<TreeNode*, int>> q;q.push(make_pair(root, 1));while(!q.empty()){TreeNode* curNode = q.front().first;int curStep = q.front().second;q.pop();//note hereif(!curNode->left && !curNode->right)return curStep;if(curNode->left)q.push(make_pair(curNode->left, curStep+1));if(curNode->right)q.push(make_pair(curNode->right, curStep+1));}}    int minDepth(TreeNode *root) {        // Start typing your C/C++ solution below        // DO NOT write int main() functionreturn BFS(root);    }};

second time

/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(root == NULL) return 0;                if(root->left == NULL) return minDepth(root->right)+1;        else if(root->right == NULL) return minDepth(root->left)+1;        else return min(minDepth(root->left), minDepth(root->right))+1;    }};


原创粉丝点击