标签:
leetcode - Lowest Common Ancestor of a Binary Search Tree
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
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).”
_______6______ / ___2__ ___8__ / \ / 0 _4 7 9 / 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
/** * 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) { int small, big; if(p->val < q->val){ small = p->val; big = q->val; } else{ small = q->val; big = p->val; }
// small = min(p->val, q->val);
// big = max(p->val, q->val); if(root->val >= small && root->val <= big) return root; else if(root->val < small) return lowestCommonAncestor(root->right, p, q); else return lowestCommonAncestor(root->left, p, q); } };
题意为找到两个节点最低的公共祖先节点。经过分析可以发现,如果一个节点左右子树中分别包含两个节点,那么这个节点一定是LCA(lowest common ancestor)。
由于是二叉搜索树,有性质:左子树节点小于根节点,右子树节点大于根节点。所以可以比较当前节点与两个节点的大小判断,从根开始遍历,第一个满足大小位于两数之间的节点,必定其“左右子树中分别包含两个节点”。
leetcode - Lowest Common Ancestor of a Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/shnj/p/4746534.html