199.二叉树的右视图
法一. BFS
class Solution {
public:
vector<int>res;
vector<int> rightSideView(TreeNode* root) {
if (!root)
return res;
queue<TreeNode*>q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; ++i) {
auto top = q.front();
if (top->left)
q.push(top->left);
if (top->right)
q.push(top->right);
q.pop();
if (i == sz - 1)
res.push_back(top->val);
}
}
return res;
}
};
法二. DFS(0ms)
class Solution {
public:
vector<int>res;
vector<int> rightSideView(TreeNode* root) {
if (!root)
return res;
dfs(root, 0);
return res;
}
void dfs(TreeNode* root, int depth) {
if (!root)
return;
if (res.size() == depth)
res.push_back(root->val);
dfs(root->right, depth + 1);
dfs(root->left, depth + 1);
}
};
572.另一个数的子树
复杂度
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (s == nullptr && t == nullptr)
return true;
if (s == nullptr || t == nullptr)
return false;
if (isSameTree(s, t))
return true;
return isSubtree(s->left, t) or isSubtree(s->right, t);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == nullptr && q == nullptr)
return true;
if (p == nullptr || q == nullptr)
return false;
if (p->val != q->val)
return false;
return isSameTree(q->left, p->left) && isSameTree(q->right, p->right);
}
};
236.二叉树的最近公共祖先
class Solution {
public:
TreeNode* ans;
bool dfs(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr) return false;
bool lson = dfs(root->left, p, q);
bool rson = dfs(root->right, p, q);
if ((lson && rson) || ((root->val == p->val || root->val == q->val) && (lson || rson))) {
ans = root;
}
return lson || rson || (root->val == p->val || root->val == q->val);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
dfs(root, p, q);
return ans;
}
};
235.二叉搜索树的最近公共祖先
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* t = root;
while(t) {
if( t->val > p->val && t->val > q->val ) t = t->left;
else if(t->val < p->val && t->val < q->val ) t = t->right;
else return t;
}
return 0;
}
};