[LeetCode] Minimum Depth of Binary Tree
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Minimum Depth of Binary Tree
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
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.
二叉樹(shù)的最小深度。
使用遞歸求解:
如果根節(jié)點(diǎn)為空,返回0。
如果左節(jié)點(diǎn)為空,遞歸計(jì)算右節(jié)點(diǎn)。
如果右節(jié)點(diǎn)為空,遞歸計(jì)算左節(jié)點(diǎn)。
返回1 + 左子樹(shù)和右子樹(shù)的最小深度。
/*** 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 == nullptr)return 0;if (root->left == nullptr)return 1 + minDepth(root->right);if (root->right == nullptr)return 1 + minDepth(root->left);return 1 + min(minDepth(root->left), minDepth(root->right));} }; // 6 ms?
轉(zhuǎn)載于:https://www.cnblogs.com/immjc/p/7682184.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的[LeetCode] Minimum Depth of Binary Tree的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 配置 CentOS 7 的网络,及重命名
- 下一篇: Donsen法则