LeetCode Algorithms #235 <Lowest Common Ancestor of a Binary Search Tree>
2016-02-02 00:16
591 查看
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
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
思路:
找到一点,它的值正好在要找的两子节点的值的中间。
如果发现当前选中的点,比两个子节点的值都大,那么要找的点在当前点的左子树中。
如果发现当前选中的点,比两个子节点的值都笑,那么要找的点在当前点的右子树中。
解:
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) { if(root == NULL || p == NULL || q == NULL) return NULL; if(p == root) return p; else if(q == root) return q; TreeNode* lagerNode = NULL; TreeNode* smallerNode = NULL; if(p->val >= root->val) { lagerNode = p; smallerNode = q; } else { lagerNode = q; smallerNode = p; } if(root->val > lagerNode->val) { return lowestCommonAncestor(root->left, p, q); } else if(root->val < smallerNode->val) { return lowestCommonAncestor(root->right, p, q); } else { return root; } } };
相关文章推荐
- VIEWGOOD(远古)边防流媒体视频系统建设项目
- 环境配置
- go lang中的import
- Go语言笔记:base64/sha1的使用
- django学习笔记(四)表单
- m3u文件转pls文件(go语言实现)
- Django时间问题
- Django REST framework的各种技巧【目录索引】
- Django REST framework的各种技巧——6.异常处理
- Django REST framework的各种技巧——7.导入导出
- Django REST framework的各种技巧——5.搜索
- Django REST framework的各种技巧——3.权限
- Django REST framework的各种技巧——4.Generic View
- Django REST framework的各种技巧——2.serializer
- Django REST framework的各种技巧——1.基础讲解
- Golang的变量常量及基本类型
- go的安装
- Mongoose学习参考文档
- 拼了个golang的常用搜索、链接导航,要的拿走
- django部署