235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:游侠对战平台mac版 编辑:程序博客网 时间:2024/05/16 10:06
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 allowa 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.
Subscribe to see which companies asked this question
这题做的不是很好。
代码
代码
/** * 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: bool findNode(TreeNode* root, TreeNode* p,vector<TreeNode*>& result) { if(root == NULL) { return false; } if(root == p) { result.push_back(root); return true; } bool temp=false; if(!temp) { result.push_back(root); temp=findNode(root->left,p,result)||findNode(root->right,p,result); if(!temp) result.pop_back(); } return temp; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { vector<TreeNode*> p1; vector<TreeNode*> p2; findNode(root,p,p1); findNode(root,q,p2); int len1=p1.size(); int len2=p2.size(); int t =min(len1,len2); while(--t>=0) { if(p1[t]==p2[t]) return p1[t]; } return p1[0]; }};
0 0
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 235.Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
- gcc g++
- DBFLOW的初使用
- oracle从入门到精通の2-启动与关闭数据库实例
- 【Java进阶一】理解封装
- 整理RHEL 6以上的NFS配置
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【leetcode】11. Container With Most Water
- 插入算法
- android拍照
- CentOS 6.5 下安装 Redis 2.8.7
- matlab中三种计算程序运行时间方法
- Ubuntu 16.04 x64搭建GitLab服务器操作笔记
- 高级搜索技巧 笔记
- 2014.08.25 大二开始