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;
    };
    

      

  • 相关阅读:
    一个简单的loading,纯属自娱自乐
    sql server CTE递归使用测试
    sql-删除无效sql链接
    sql-按周输出每月的周日期范围
    sql-计算每个月星期几有几天
    sql-GOTO跳转
    回滚与撤销
    数据库事务
    mysql 海量数据的存储和访问解决方案
    数据库范式
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842112.html
Copyright © 2011-2022 走看看