持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第18天,点击查看活动详情
687. 最长同值路径
思路:
返回max(左节点,右节点), ans = max(ans, 左节点 + 右节点)
代码:
public:
int ans = 0;
int getmax(TreeNode*root) {
if (root == nullptr) return 0;
int left = getmax(root->left);
int right = getmax(root->right);
int leftarrow = 0,rightarrow = 0;
if (root->left && root->left->val == root->val) {
leftarrow += left + 1;
}
if (root->right && root->right->val == root->val) {
rightarrow += right + 1;
}
ans = max(ans, leftarrow + rightarrow);
return max(leftarrow, rightarrow) ;
}
int longestUnivaluePath(TreeNode* root) {
getmax(root);
return ans;
}
};
129. 求根节点到叶节点数字之和
思路:
左节点的数 + 右节点的数
代码:
class Solution {
public:
int sumtotal(TreeNode* rooc, int sum) {
if (rooc == nullptr) return 0;
sum = sum * 10 + rooc->val;
if (rooc->left == nullptr && rooc->right == nullptr) return sum;
return sumtotal(rooc->left, sum) + sumtotal(rooc->right, sum);
}
int sumNumbers(TreeNode* root) {
return sumtotal(root, 0);
}
};
404. 左叶子之和
思路:
左节点满足(它没有左右孩子)
代码:
class Solution {
public:
int sum = 0;
void lefttree(TreeNode*root) {
if (root == nullptr) return;
if (root->left && !root->left->left && !root->left->right) {
sum += root->left->val;
}
lefttree(root->left);
lefttree(root->right);
}
int sumOfLeftLeaves(TreeNode* root) {
lefttree(root);
return sum;
}
};
230. 二叉搜索树中第K小的元素
思路:
可以用数组存储,或者直接中序遍历找
代码:
class Solution {
public:
int c,count;
void getmin(TreeNode*root) {
if (root == nullptr) return;
getmin(root->left);
count-=1;
if (count == 0) {
c = root->val;
return;
}
getmin(root->right);
}
int kthSmallest(TreeNode* root, int k) {
count = k;
getmin(root);
return c;
}
};
173. 二叉搜索树迭代器
思路:
二叉搜索树的中序遍历序列是单调递增的。 利用二叉树的迭代方式的中序遍历,保存左子链,从而使用O(h)的内存。
代码:
class BSTIterator {
private:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) {
return;
}
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
vector<int> arr;
int idx;
public:
BSTIterator(TreeNode* root): idx(0), arr(inorderTraversal(root)) {}
int next() {
return arr[idx++];
}
bool hasNext() {
return (idx < arr.size());
}
};