日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

【Minimum Depth of Binary Tree】cpp

發(fā)布時(shí)間:2025/3/19 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Minimum Depth of Binary Tree】cpp 小編覺(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.

代碼:

/*** 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) return 0;if ( !root->left && !root->right) return 1;if ( root->left && root->right ) return std::min( Solution::minDepth(root->left)+1, Solution::minDepth(root->right)+1);if ( root->left ) return Solution::minDepth(root->left)+1;if (root->right ) return Solution::minDepth(root->right)+1;} };

tips:

深搜思路(遞歸實(shí)現(xiàn))。這里需要控制向下進(jìn)行的條件。

1. 如果root是NULL,返回0

2. 如果root不是NULL,且left和right都是NULL,則到達(dá)葉子節(jié)點(diǎn)返回1(代表算上葉子節(jié)點(diǎn)的那一層)

3. 如果root->left和root->right都不為NULL,則繼續(xù)往兩邊深搜

4. 如果root不是NULL,但root->left或root->right哪一方為NULL,則為NULL的一端不會(huì)再有葉子節(jié)點(diǎn)出現(xiàn),不能再往下走了。

完畢。

============================================

第二次過(guò)這道題,上來(lái)沒(méi)有把終止條件想完全。終止條件應(yīng)該是達(dá)到葉子簡(jiǎn)單root->left root->right都為空。

修改了一次后AC了。

/*** 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 ) return 0;int min_depth = INT_MAX;Solution::depth(root, min_depth, 1);return min_depth;}static void depth(TreeNode* root, int& min_depth, int dep){if ( !root->left && !root->right ) min_depth = min(min_depth,dep); if ( root->left ) Solution::depth(root->left, min_depth, dep+1);if ( root->right ) Solution::depth(root->right, min_depth, dep+1);} };

?

轉(zhuǎn)載于:https://www.cnblogs.com/xbf9xbf/p/4508762.html

總結(jié)

以上是生活随笔為你收集整理的【Minimum Depth of Binary Tree】cpp的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。