Skip to content

Files

Latest commit

 

History

History
107 lines (75 loc) · 3.37 KB

236-lowest-common-ancestor-of-a-binary-tree.md

File metadata and controls

107 lines (75 loc) · 3.37 KB

236. Lowest Common Ancestor of a Binary Tree - 二叉树的最近公共祖先

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。

示例 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

 

说明:

  • 所有节点的值都是唯一的。
  • p、q 为不同节点且均存在于给定的二叉树中。

题目标签:Tree

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 8 ms 3 MB
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* node, TreeNode* target, vector<TreeNode*>& path, bool& ret) {
        if (!node || ret) return;

        if (!ret && node == target) {
            ret = true;
        }

        path.push_back(node);

        if (!ret && node->left) {
            dfs(node->left, target, path, ret);
        }
        if (!ret && node->right) {
            dfs(node->right, target, path, ret);
        }

        if (!ret) {
            path.pop_back();
        }
    }

    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL) return NULL;

        vector<TreeNode*> pp;
        bool r1 = false;
        dfs(root, p, pp, r1);

        vector<TreeNode*> pq;
        bool r2 = false;
        dfs(root, q, pq, r2);

        int i = 0;
        for (; i < pp.size() && i < pq.size() && pp[i] == pq[i]; ++i) ;
        i--;  // main reason for runtime error
        // runtime error: member access within misaligned address 0x000000000021 for type 'struct TreeNode', which requires 8 byte alignment
        return pp[i];
        
    }
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();