后续遍历-二叉树的最近公共祖先
2023-08-18 本文已影响0人
1哥
236. 二叉树的最近公共祖先
要点:
1.自低向上==> 后序遍历
- 根据左右子节点是否分别是p,q.判断当前节点是否是公共祖先
- 当前节点是p,q 则返回当前节点。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if(root == p || root == q || root == NULL)
return root;
struct TreeNode* left = lowestCommonAncestor(root->left, p, q);
struct TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right)
return root;
else if (left)
return left;
else
return right;
}