二叉數的最小深度:
思路:和最大深度一樣需要用到回溯遞歸的方法
代碼大致內容
判斷函數是否為空,如果是空return 0;
定義一個變量接收遞歸函數返回的值(左)
定義一個變量接收遞歸函數返回的值(右)
判斷如果函數左邊為null但是右邊不是null表示沒用到最終位置所以返回一個rightdepth+1;
同理右邊就返回左邊加1
如果滿的就返回兩個之中的最小值
看代碼:
class Solution {
public:int getDepth(TreeNode* node) {if (node == NULL) return 0;int leftDepth = getDepth(node->left); // 左int rightDepth = getDepth(node->right); // 右// 中// 當一個左子樹為空,右不為空,這時并不是最低點if (node->left == NULL && node->right != NULL) { return 1 + rightDepth;} // 當一個右子樹為空,左不為空,這時并不是最低點if (node->left != NULL && node->right == NULL) { return 1 + leftDepth;}int result = 1 + min(leftDepth, rightDepth);return result;}int minDepth(TreeNode* root) {return getDepth(root);}
};
?
下題為節點數量統計:
很簡單
思路:首先定義一個變量count = 0;
代碼內容:首先判讀是否為空,空則返回count
count = 遞歸左邊
count =遞歸右邊
最后return count + 1;
代碼意義:所有遞歸除了為空,都會使count + 1,而兩個遞歸可以遍歷所有的節點
這樣就可以計算出來所有的節點數量
看代碼:
class Solution {
public:
? ? int count = 0;
? ? int countNodes(TreeNode* root)
? ? {
? ? ? ?
? ? ? ? if(root == nullptr)return count;;
? ? ? ? count = countNodes(root -> left);
? ? ? ? count = countNodes(root -> right);
? ? ? ? return count + 1;
? ? }
};