目录
LeeCode 110.平衡二叉树
LeeCode 257. 二叉树的所有路径
LeeCode 404.左叶子之和
总结
LeeCode 110.平衡二叉树
思路:通过递归,使用后序遍历,将当前节点的左右子树高度向上传,若高度差 > 1,说明二叉树不平衡,返回-1。
class Solution {
public:
bool isBalanced(TreeNode* root) {
return getHeight(root) == -1 ? false : true;
}
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;
return abs(leftHeight - rightHeight) > 1 ? -1 : 1 + max(leftHeight,rightHeight);
}
};
LeeCode 257. 二叉树的所有路径
思路:
前序遍历找到从父节点到叶子节点对应的路径,通过回溯来回退一个路径再进入另一个路径。
class Solution {
private:
void traversal(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) {
traversal(cur->left, path, result);
path.pop_back();
}
if (cur->right) {
traversal(cur->right, path, result);
path.pop_back();
}
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
vector<int> path;
if (root == NULL) return result;
traversal(root, path, result);
return result;
}
};
LeeCode 404.左叶子之和
思想:判断当前节点是否为左叶子节点——直接是无法判断的,需要借助父节点。若该结点的左节点不为空,且该结点的左节点的左右节点都为空,则这个节点的左节点就是左叶子节点。
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 0;
int leftValue = sumOfLeftLeaves(root->left);
if (root->left && !root->left->left && !root->left->right) {
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};
总结
1.求二叉树的深度适合用前序遍历,求高度适合用后序遍历。
2.回溯和递归要永远在一起。
3.判断是否为叶子节点,需要借助其父节点。