leetcode - Lowest Common Ancestor of a Binary Search Tree
2015-08-20 23:23
357 查看
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).”
For example, the lowest common ancestor (LCA) of nodes
题意为找到两个节点最低的公共祖先节点。经过分析可以发现,如果一个节点左右子树中分别包含两个节点,那么这个节点一定是LCA(lowest common ancestor)。
由于是二叉搜索树,有性质:左子树节点小于根节点,右子树节点大于根节点。所以可以比较当前节点与两个节点的大小判断,从根开始遍历,第一个满足大小位于两数之间的节点,必定其“左右子树中分别包含两个节点”。
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
2and
8is
6. Another example is LCA of nodes
2and
4is
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)。
由于是二叉搜索树,有性质:左子树节点小于根节点,右子树节点大于根节点。所以可以比较当前节点与两个节点的大小判断,从根开始遍历,第一个满足大小位于两数之间的节点,必定其“左右子树中分别包含两个节点”。
相关文章推荐
- Hibernate(四)——缓存策略+lazy
- C++实现KMP模式匹配算法
- iOS系统和XCode各版本发布日期
- IOS开发札记
- Linux Shell 编程实战技巧
- ssh-key 与 git账户配置以及多账户配置
- Reverse Linked List II
- C++ 小技巧之一条语句多行书写
- iOS网络监控— BMReachability
- B树、B-树、B+树、B*树
- ios webview自适应实际内容高度4种方法
- YII2.0 Activeform表单组件的使用方法
- NOIP2010-普及组复赛-第二题-接水问题
- Struts2笔记――3.配置处理结果
- POJ3693Maximum repetition substring【后缀数组】
- java io详解
- pull解析与生成xml文件
- Codeforces Round #285(Div.2) A,B,C 解题报告
- Leetcode: Ugly Number II
- Pascal's Triangle II