LeetCode 111: Minimum Depth of Binary Tree

来源:互联网 发布:上古卷轴5梦璃捏脸数据 编辑:程序博客网 时间:2024/05/16 03:07

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.

解题思路

思路一:采用递归的思想,分别求左右子树的最小高度;然后返回最小高度加1(注意,需要特别考虑只有一个子女的情况)。代码如下:

/** * 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;        int leftH = minDepth(root->left);        int rightH = minDepth(root->right);        if (leftH == 0) return rightH + 1;        if (rightH == 0) return leftH + 1;        return min(leftH, rightH) + 1;    }};

思路二:对二叉树进行按层遍历,如果在某一层发现了一个叶子节点,那么就找到了最小深度,此时返回当前深度即可。代码如下:

/** * 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;        int height = 0;        queue<TreeNode *> nodeQueue;        nodeQueue.push(root);        while (!nodeQueue.empty()) {            height++;            int levelSize = nodeQueue.size();            for (int i = 0; i < levelSize; ++i) {                TreeNode *front = nodeQueue.front();                if (front->left == NULL && front->right == NULL) {                    // 在某一层发现了一个叶子节点,那么就找到了最小深度                    return height;                }                nodeQueue.pop();                if (front->left != NULL) nodeQueue.push(front->left);                if (front->right != NULL) nodeQueue.push(front->right);            }        }    }};
0 0
原创粉丝点击