minimum-depth-of-binary-tree (搜索)
生活随笔
收集整理的這篇文章主要介紹了
minimum-depth-of-binary-tree (搜索)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題意:輸出一個二叉樹的最小深度。
思路:搜索一下就行了。
注意:搜索的時候,是比較每個子樹的左右子樹的大小,每個子樹的深度要加上根節(jié)點!
class Solution { public:int run(TreeNode *root) {if (root == NULL) return 0; //空樹if (root->left == NULL) return run(root->right) + 1;if (root->right == NULL) return run(root->left) + 1;int left = run(root->left);int right = run(root->right);return (left < right) ? (left+1) : (right+1);} };?
兄弟題
?maximum-depth-of-binary-tree
題意:輸出最大的二叉樹的深度
class Solution { public:int maxDepth(TreeNode *root) {if (root == NULL)return 0;if (root->left == NULL) maxDepth(root->right) + 1;if (root->right == NULL)maxDepth(root->left) + 1;int left = maxDepth(root->left) + 1;int right = maxDepth(root->right) + 1;return left > right ? left : right;} };?
轉載于:https://www.cnblogs.com/ALINGMAOMAO/p/9903737.html
總結
以上是生活随笔為你收集整理的minimum-depth-of-binary-tree (搜索)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java IO框架总揽--ObjectI
- 下一篇: Nginx反代Mogilefs分布式储存