zoukankan      html  css  js  c++  java
  • 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;
    
    }
  • 相关阅读:
    Spring Boot 缓存技术:Spring Boot
    Java基础之Iterable接口
    使用sqlyog连接 Mysql 出现1251错误
    IDEA更改主题插件——Material Theme UI详解
    免安装版的Mysql
    使用Nexus搭建Maven私服
    Spring之注解注入bean
    Idea springboot 配置热部署
    Spring Boot 异常处理与单元测试
    Ubuntu20.04在线安装VMware-Tools
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3423536.html
Copyright © 2011-2022 走看看