zoukankan      html  css  js  c++  java
  • LeetCode 111. Minimum Depth of Binary Tree

    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.

    给你一个二叉树,找到它的最浅深度

    这个题目我采取的是用深度遍历的方法,把每次得到的深度保存起来即depth,如果depth小于len,我们就令len为depth,遍历整个二叉树

    后得到的len就是最浅深度

    /**
     * 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:
        void depthFirstSearch(TreeNode* root, int depth)
    	{
    		if (root == NULL)return;
    		if (root->left)
    		{
    			depthFirstSearch(root->left, ++depth);
    			depthFirstSearch(root->right, depth);
    		}
    		else
    		{
    			if (root->right)
    			{
    				depthFirstSearch(root->right, ++depth);
    			}
    			else
    			{
    				if (++depth < len)len = depth;
    			}
    		}
    	}
    	int minDepth(TreeNode* root) {
    		int depth = 0;
    		depthFirstSearch(root, depth);
    		if(len==INT32_MAX)
    		return 0;
    		else
    		return len;
    	}
    private:
    	int len = INT32_MAX;
    };
    

      

  • 相关阅读:
    MySql不允许对同一张表同时进行查询和更新
    MysSql 显示不了中文、乱码问题
    SpringBoot参数访问
    那些年我看过的好文
    关于远程调试
    算法题
    Spring Boot 注解学习
    linux 设置ssh免密登录
    ORA各种错误
    listener.ora tnsnames.ora
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842112.html
Copyright © 2011-2022 走看看