Day21_二叉树
26. 二叉树的最近公共祖先
236. 二叉树的最近公共祖先
思路:
后序遍历二叉树,找到目标结点立即返回,如果某个结点的左右子树返回值都不为空,则最近公共祖先找到了,返回当前结点的值
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
if (left && right == NULL) return left;
else if (left == NULL && right) return right;
else return NULL;
}
};
28. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先
思路1:
二叉搜索树也是二叉树,可以直接用找二叉树最近公共祖先的方法找到二叉搜索树的最近公共祖先。
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL || root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
else if (left && right == NULL) return left;
else if (left == NULL && right) return right;
else return NULL;
}
};
思路2:
二叉搜索树是有序的,中序遍历结果升序,于是p,q的公共祖先就在区间[p,q]中,根据二叉搜索树的中序遍历,p,q区间内的第一个结点就是p,q的最近公共祖先
递归法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val > p->val && root->val > q->val) // 去左子树找
return lowestCommonAncestor(root->left, p, q);
else if (root->val < p->val && root->val < q->val) // 去右子树找
return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
迭代法
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root) {
if (root->val > p->val && root->val > q->val) // 去左子树找
root = root->left;
else if (root->val < p->val && root->val < q->val) // 去右子树找
root = root->right;
else return root;
}
return NULL;
}
};
29. 二叉搜索树中的插入操作
701. 二叉搜索树中的插入操作
思路:
利用二叉搜索树的性质,查找目标值,找到空结点位置插入目标值即可。
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (root == NULL) {
TreeNode* node = new TreeNode(val);
return node;
}
if (root->val > val) root->left = insertIntoBST(root->left, val);
else if (root->val < val) root->right = insertIntoBST(root->right, val);
return root;
}
};