235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:慕课平台有哪些 知乎 编辑:程序博客网 时间:2024/05/17 17:57
LeetCode里关于树的题似乎很多都用递归做比较好,这道题用常规方法比较麻烦,但是用递归就很简洁(看了答案才醒悟……)
递归解法如下(注意题中给出的是BST,左子节点的键值<根节点的键值<右子节点的键值):
/** * 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 (p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left, p, q); else if (p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right, p, q); else return root; }};
阅读全文
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
- 131. Palindrome Partitioning
- leetcode 128. Longest Consecutive Sequence
- Head First设计模式之迭代器模式
- No valid bower.json was found in any branch ...
- Python字符串格式化--format()方法
- 235. Lowest Common Ancestor of a Binary Search Tree
- 数据结构C语言链栈
- 51Nod 1384 全排列(next-permutation)
- P1308 统计单词数
- java中String数组和List的互相转化
- 下载一个电影,普通下载方式和utorrent方式,速度为什么差这么多?原理是什么?
- kdelibs的大致介绍
- 20170910WindowsPrj06_注册表操作
- 51Nod 2006 飞行员配对(二分图最大匹配) 匈牙利算法