【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree (2 solutions)
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).”
_______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.
解法一:不考虑BST的特性,对于一棵普通二叉树,寻找其中两个节点的LCA
深度遍历到节点p时,栈中的所有节点即为p的从根开始的祖先序列。
因此只需要比较p、q祖先序列中最后一个相同的祖先即可。
/** * 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) { // special cases if(root == NULL) return NULL; if(p == root || q == root) return root; if(p == q) return p; vector<TreeNode*> vp; vector<TreeNode*> vq; stack<TreeNode*> stk; unordered_map<TreeNode*, bool> m; //visited stk.push(root); m[root] = true; while(!stk.empty()) { TreeNode* top = stk.top(); if(top->left && m[top->left] == false) { stk.push(top->left); m[top->left] = true; if(top->left == p) { vp = stkTovec(stk); if(!vq.empty()) break; } if(top->left == q) { vq = stkTovec(stk); if(!vp.empty()) break; } continue; } if(top->right && m[top->right] == false) { stk.push(top->right); m[top->right] = true; if(top->right == p) { vp = stkTovec(stk); if(!vq.empty()) break; } if(top->right == q) { vq = stkTovec(stk); if(!vp.empty()) break; } continue; } stk.pop(); } int i = 0; for(; i < vp.size() && i < vq.size(); i ++) { if(vp[i] != vq[i]) break; } return vp[i-1]; } vector<TreeNode*> stkTovec(stack<TreeNode*> stk) { vector<TreeNode*> v; while(!stk.empty()) { TreeNode* top = stk.top(); stk.pop(); v.push_back(top); } reverse(v.begin(), v.end()); return v; } };
解法二:利用BST的性质,
p和q的LCA是恰好把p、q分叉的节点,也就是LCA的值介于p、q之间
从最高层的祖先root开始往下,
若不满足LCA条件,往p、q所在子树递归。
/** * 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->val - p->val) * (root->val - q->val) <= 0) return root; else if(root->val > p->val) return lowestCommonAncestor(root->left, p, q); else return lowestCommonAncestor(root->right, p, q); } };