[Leetcode235] 二叉搜尋樹的最近公共祖先
阿新 • • 發佈:2018-11-27
給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。
這道題一定要了解二叉搜尋樹的性質,右邊比左邊大。
python:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if root == None: return None if (p.val <= root.val and root.val <= q.val) or (q.val <= root.val and root.val <= p.val): return root if (p.val < root.val) and (q.val < root.val): return self.lowestCommonAncestor(root.left,p,q) if (p.val > root.val) and (q.val > root.val): return self.lowestCommonAncestor(root.right,p,q)
C++:
/** * 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) return NULL; if((root->val>=p->val&&root->val<=q->val) || (root->val>=q->val&&root->val<=p->val)) return root; if(root->val>p->val&&root->val>q->val) return lowestCommonAncestor(root->left,p,q); if(root->val<p->val&&root->val<q->val) return lowestCommonAncestor(root->right,p,q); return NULL; } };