leetcode | Minimum Depth of Binary Tree

来源:互联网 发布:美妆软件哪个好 编辑:程序博客网 时间:2024/05/01 20:17

rMinimum Depth of Binary Tree : https://leetcode.com/problems/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,
最短路径(最小深度)则是选择左右子树中深度小的加 1。
需要注意的是,空节点不算叶节点,所以遇到空节点子树时,需要返回另一颗子树的深度加 1;在求树的深度时,选的是深度较大的一个,故不需考虑空节点子树
如:[1 2 NULL] 返回 2

/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //定义:NULL不是叶节点class Solution {public:    int minDepth(TreeNode* root) {        if (root == NULL)            return 0;        if (root->left == NULL) // 左子树没有叶节点            return minDepth(root->right)+1;        if (root->right == NULL) // 右子树没有叶节点            return minDepth(root->left)+1;        return min(minDepth(root->left), minDepth(root->right)) + 1;    }};
0 0
原创粉丝点击