【LeetCode】LeetCode 236.二叉树的最近公共祖先

LeetCode 236.二叉树的最近公共祖先

题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

题目

【LeetCode】LeetCode 236.二叉树的最近公共祖先_第1张图片

【LeetCode】LeetCode 236.二叉树的最近公共祖先_第2张图片

解答

求最小公共祖先,需要自底向上,如果是二叉树,那么只能通过后序遍历(即回溯)实现自底向上的遍历方式

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root == p || root == q || root == NULL)  return root;
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);

        if(left != NULL && right != NULL)   return root;
        if(left == NULL && right != NULL)   return right;
        return left;
    }
};

你可能感兴趣的:(#,二叉树专题,leetcode,算法,职场和发展)