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

    题目解答:

    这道题借助了之前做的层次遍历的题目的代码,增加了一个判断条件,如果可以确定当前节点是叶子节点,则返回其深度,也就是找到的最近的叶子节点的深度。

    代码如下:

    /**
     * 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:
        int minDepth(TreeNode* root) {
            int depth = 0;
            int curnum = 0;
            int childnum = 0;
            if(root == NULL)
            {
                return 0;
            }
            queue<TreeNode *> TreeQueue;
            TreeQueue.push(root);
            curnum = 1;
            while(curnum != 0)
            {
                vector<int> tmp;
                depth++;
                while(curnum != 0)
                {
                    TreeNode *p = TreeQueue.front();
                    tmp.push_back(p -> val);
                    if((p -> left == NULL) && (p -> right == NULL))
                    {
                        return depth;
                    }
                    if(p -> left != NULL)
                    {
                        TreeQueue.push(p -> left);
                        childnum++;
                    }
                    if(p -> right != NULL)
                    {
                        TreeQueue.push(p -> right);
                        childnum++;
                    }
                   
                    TreeQueue.pop();
                    curnum--;
                }
                curnum = childnum;
                childnum = 0;
            }
            return depth;
        }
    };

  • 相关阅读:
    实验一 GIT 代码版本管理
    实验五、单元测试
    实验四 代码审查
    结对编程 第二阶段
    结对编程第一阶段
    结对编程(一)
    实验1 GIT代码版本管理
    实验五 单元测试
    实验四 代码评审
    实验三 UML建模工具的安装与使用
  • 原文地址:https://www.cnblogs.com/CodingGirl121/p/5431213.html
Copyright © 2011-2022 走看看