題1:
指路:LeetCode110 平衡二叉樹
思路與代碼:
左右子樹的高度差小于等于1。對于這個題,遞歸比迭代方便太多,我也想過迭代,但是我沒有寫出來,大家可以自己試一下。遞歸代碼如下:
class Solution {
public://遞歸int getHeight (TreeNode* node) {if (node == NULL) {return 0;}int leftHeight = getHeight(node->left);if (leftHeight == -1) return -1;int rightHeight = getHeight(node->right);if (rightHeight == -1) return -1;int ans = abs(leftHeight - rightHeight);if (ans > 1) return -1; // 絕對值超過1符合條件else return 1 + max(leftHeight, rightHeight);/* return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight, rightHeight);*/} bool isBalanced(TreeNode* root) {if (getHeight(root)== -1) return false;return true;/*return getHeight(root) == -1 ? false : true;*/}
};
題2:
指路:LeetCode257 二叉樹的所有路徑
思路與代碼:
遞歸進行前序遍歷,找到子節點記錄路徑之后回溯回退路徑。我還沒會呢,先看看代碼吧。
class Solution {
private:void treversal(TreeNode* cur, vector<int>& path, vector<string>& result) {path.push_back(cur->val);if (cur->left == NULL && cur->right == NULL) {string sPath;for (int i = 0; i < path.size() - 1; i++) {sPath += to_string(path[i]);sPath += "->";}sPath += to_string(path[path.size() - 1]);result.push_back(sPath);return ;}if (cur->left) {treversal(cur->left, path, result);path.pop_back();}if (cur->right) {treversal(cur->right, path, result);path.pop_back();}}public:vector<string> binaryTreePaths(TreeNode* root) {vector<string> result;vector<int> path;if (root == NULL) return result;treversal(root, path, result);return result;}
};