257. Binary Tree Paths
class Solution {
private:
void dfs(TreeNode *root, string current, vector<string> &ret) {
string next = current;
if (current != "") next += "->";
next += to_string(root->val);
if (!root->left && !root->right) {
ret.push_back(next);
return;
}
if (root->left) dfs(root->left, next, ret);
if (root->right) dfs(root->right, next, ret);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> ret;
if (!root) return ret;
dfs(root, "", ret);
return ret;
}
};
236. Lowest Common Ancestor of a Binary Tree
class Solution {
private:
bool dfs(TreeNode *root, TreeNode *p, TreeNode *q, TreeNode **ret) {
int is_left = 0;
int is_right = 0;
int is_root = (root == p || root == q);
if (root->left) is_left = dfs(root->left, p, q, ret);
if (root->right) is_right = dfs(root->right, p, q, ret);
int sum = is_left + is_right + is_root;
if (sum == 2 && *ret == nullptr) *ret = root;
return sum;
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return root;
TreeNode *ret = nullptr;
dfs(root, p, q, &ret);
return ret;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
return left ? (right? root: left): right;
}
};