leecode 解题总结:111. Minimum Depth of Binary Tree

来源:互联网 发布:mssql数据库 查询语句 编辑:程序博客网 时间:2024/05/21 17:49
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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.分析:题目是求二叉树的最小深度。从根节点到最近的叶子结点距离。可以维护一个最短距离,如果当前正在遍历的结点的距离 >= 最短距离,则后面就无需遍历,直接返回。但是需要遍历完所有的路径。可以认为最短距离必定是在根节点的左孩子的最短距离或者右孩子的最短距离中。之前我们计算二叉树的高度是: 左右孩子结点高度的较大值 + 1.可以直接改成左右孩子结点高度的较小值 + 1报错:Input:[1,2]Output:1Expected:2关键:1 题目中所说的叶子结点限定了返回左右孩子结点高度的较小 + 1错误,需要继续补充叶子结点的判定。如果当前结点两个孩子都为空,则当前结点就是叶节点,就是候选结果集,返回高度1即可,因为本身占据一层的高度如果当前结点左孩子非空,左孩子有可能是叶节点,所以继续递归计算高度;否则,左孩子是空结点,没有必要计算同理右孩子结点。2在当前结点不是叶子结点时:计算左右孩子结点高度较小值 + 1当前结点是叶子结点:返回1*/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){return 0;}int leftHeight = INT_MAX;int rightHeight = INT_MAX;//当前结点是叶子结点,是候选结果集之1,返回高度为1if(NULL == root->left && NULL == root->right){return 1;}//如果当前结点左孩子不空,才会选取当前结点作为候选结果集if(root->left){leftHeight = minDepth(root->left);}if(root->right){rightHeight = minDepth(root->right);}//如果当前结点的两个孩子都为空,那么当前结点就是叶子结点,return (min( leftHeight , rightHeight ) + 1);    }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } }}int main(int argc , char* argv[]){process();getchar();return 0;}

0 0
原创粉丝点击