• LeetCode OJ——Minimum Depth of Binary Tree


    http://oj.leetcode.com/problems/minimum-depth-of-binary-tree/

    贡献了一次runtime error,因为如果输入为{}即空的时候,出现了crash。其实这种情况也处理了,但是顺序不对,如下:

    if(root->left == NULL && root->right == NULL)
                return 1;

    if(root==NULL )
    return 0;
    如果输入是空的话,会对空->left访问left,但这是错误的。所以,应该先判断是否为空。即把两个if换个顺序就好了。

    广搜,一直到有个点是叶子节点,然后返回深度。经过两道类似的题目,word ladder,求最小深度的时候,优先使用广搜。

    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    struct TreeNode {
       int val;
       TreeNode *left;
       TreeNode *right;
       TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    
    class Solution {
    public:
        int minDepth(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(root==NULL )
                return 0;
            if(root->left == NULL && root->right == NULL)
                return 1;
    
    
            queue<pair<TreeNode* ,int > > nodeQueue;
            nodeQueue.push(make_pair(root,1));
    
            int templen = 0;
            TreeNode* topNode;
    
            while(!nodeQueue.empty())
            {
                topNode = nodeQueue.front().first;
                templen =  nodeQueue.front().second;
                nodeQueue.pop();
    
                if(topNode->left == NULL && topNode->right == NULL)
                    return templen;
    
                if(topNode->left)
                    nodeQueue.push(make_pair(topNode->left,templen+1));
                if(topNode->right)
                    nodeQueue.push(make_pair(topNode->right,templen+1));
    
            }
             
        }
    };
    
    
    
    int main()
    {
        TreeNode *n0 = new TreeNode(0);
        TreeNode *n1 = new TreeNode(2);
        n0->left = n1;
        TreeNode *n2,*n3;;
        Solution mysolution;
        cout<<mysolution.minDepth(NULL);
        
        return 0;
    
    }
  • 相关阅读:
    RSA使用
    C#获取主机信息
    NSIS打包软件使用
    C#获取局域网主机
    C#实现Web链接启动应用程序
    4.布局介绍
    Server Sql 多表查询、子查询和分页
    C# File类常用方法
    Vue 使用技巧手记
    前端面试题手记
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3423536.html
Copyright © 2020-2023  润新知