题1:
指路:LeetCode110 平衡二叉树
思路与代码:
左右子树的高度差小于等于1。对于这个题,递归比迭代方便太多,我也想过迭代,但是我没有写出来,大家可以自己试一下。递归代码如下:
cpp
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 二叉树的所有路径
思路与代码:
递归进行前序遍历,找到子节点记录路径之后回溯回退路径。我还没会呢,先看看代码吧。
cpp
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;
}
};