Lowest Common Ancestor of a Binary Tree

来源:互联网 发布:雅思知乎 编辑:程序博客网 时间:2024/06/05 02:48
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

_______3______
/ \
___5__ ___1__
/ \ / \
6 _2 0 8
/ \
7 4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

思路:题目给定一个二叉树和两个节点指针p和q。要求返回节点p和q的公共祖先节点,题目假定给定的节点是有效的,都是在树中的节点

(1)对于一个节点root,如果root为NULL或者root等于p或者q的话,这个时候root就是需要求出的节点

(2)如果p和q都在p的一侧且root不为p和q,则root一定不是最低的公共祖先

(3)当p和q分居在root的两侧的时候,这个时候root即为所求(递归从下到上,第一次分在左右的时候即为所求)

代码如下:

/** * 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:    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {        if(!root || 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;        return left?left:right;    }};


0 0