題1:
指路:LeetCode104 二叉樹的最大深度
思路與代碼:
1.遞歸
求左右子樹的最大深度后加1(根到子樹也有1個深度單位)。代碼如下:
class Solution {
public:int maxDepth(TreeNode* root) {int ans = 0;if (root == NULL) return 0;int leftdepth = maxDepth(root->left);int rightdepth = maxDepth(root->right);ans = max(leftdepth, rightdepth) + 1;return ans;}
};
2.迭代(層序遍歷)
見二叉樹的層序遍歷。代碼如下:
class Solution {
public:int maxDepth(TreeNode* root) {if (root == NULL) return 0;int depth = 0;queue<TreeNode*> que; // 隊列用來放節點que.push(root);while (!que.empty()) {int size = que.size();depth++; // 向下一層深度加1while (size--) {TreeNode* node = que.front();que.pop();if (node->left) que.push(node->left);if (node->right) que.push(node->right);}}return depth;}
};
題2:
指路:LeetCode111 二叉樹的最小深度
思路與代碼:
最小深度應注意當左子樹和右子樹都為空時的限制條件。代碼如下:
class Solution {
public:int minDepth(TreeNode* root) {queue<TreeNode*> que;if (root == NULL) return 0;que.push(root);int depth = 0;//vector<int> vec;while (!que.empty()) {int size = que.size();// vec.push_back(size);depth++;while (size--) {TreeNode* node = que.front();que.pop();if (node->left) que.push(node->left);if (node->right) que.push(node->right);if (!node->left && !node->right) {return depth;}} }return depth;}
};
題3:
指路:LeetCode222 完全二叉樹的節點個數
思路與代碼:
差異不大,統計一下size就行。代碼如下:
class Solution {
public:int countNodes(TreeNode* root) {queue<TreeNode*> que; if(root == NULL) return 0;que.push(root);int ans = 0;while (!que.empty()) {int size = que.size();ans += size;while (size--) {TreeNode* node = que.front();que.pop();// ans++;if (node->left) que.push(node->left);if (node->right) que.push(node->right);}}return ans;}
};