zoukankan      html  css  js  c++  java
  • 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.

    注意与求树的高度的区别。

    C++实现代码:

    #include<iostream>
    #include<new>
    #include<vector>
    using namespace std;
    
    //Definition for binary tree
    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)
            {
                if(root->left==NULL&&root->right==NULL)
                    return 1;
                int lmin=minDepth(root->left);
                int rmin=minDepth(root->right);
                if(root->left&&root->right==NULL)
                    return lmin+1;
                if(root->left==NULL&&root->right)
                    return rmin+1;
                return (lmin<= rmin)?(lmin+1):(rmin+1);
            }
            return 0;
        }
        void createTree(TreeNode *&root)
        {
            int i;
            cin>>i;
            if(i!=0)
            {
                root=new TreeNode(i);
                if(root==NULL)
                    return;
                createTree(root->left);
                createTree(root->right);
            }
        }
    };
    int main()
    {
        Solution s;
        TreeNode *root;
        s.createTree(root);
        cout<<s.minDepth(root)<<endl;
    }
  • 相关阅读:
    函数的有用信息,装饰器 day12
    函数名、闭包、装饰器 day11
    函数的动态参数与命名空间 day10
    函数 day9
    集合 day8
    文件操作 day8
    基础数据类型补充,及capy daty7
    day7 回顾
    编码补充 daty 6
    字典的增删改查 daty 5
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4115282.html
Copyright © 2011-2022 走看看