111. Minimum Depth of Binary Tree(DFS)

来源:互联网 发布:数控编程招聘的视频 编辑:程序博客网 时间:2024/06/05 04:40

1. Description

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.


2. Code

题目比较简单,与寻找最大depth类似。逐层寻找叶节点,第一次找到的那个就是最小深度的叶节点。记录一下代码而已。

/** * 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) {        if(root == NULL) return 0;        if(root->left == NULL && root->right == NULL) return 1;        TreeNode * node = NULL;        int level = 0;        queue<TreeNode*> tmp;        tmp.push(root);        while( !tmp.empty()) {            level ++;            for(int i = 0, size = tmp.size(); i < size; i++) {                node = tmp.front();                tmp.pop();                if(node->left == NULL && node->right == NULL)                    return level;                if(node->left != NULL) {                    tmp.push(node->left);                }                if(node->right != NULL) {                    tmp.push(node->right);                }                       }           }        return level;       }};
原创粉丝点击