https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
初步代码(没有考虑到二叉搜索树左小右大的性质)(10ms72%)
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
double route1 = search(root,p,1);//用int当树过大会溢出,所以改为double(权宜之计,待优化)
double route2 = search(root,q,1);
TreeNode node = root;
char[] c1 = (route1+"").toCharArray();
char[] c2 = (route2+"").toCharArray();
int len=c1.length<c2.length?c1.length:c2.length;
for(int i=1;i<len;i++)
{
if(c1[i]==c2[i])
{
if(c1[i]=='1') node=node.left;
else if(c1[i]=='0') node=node.right;
}
else if (c1[i]!=c2[i]) break;
}
return node;
}
private double search(TreeNode root,TreeNode node,double x)
{
if(root==null) return 0;
if(node.val==root.val) return x;
return(search(root.left,node,x*10+1)+search(root.right,node,x*10));
}
}
优化思路
1.利用二叉搜索树的性质重写流程
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val<p.val&&root.val<q.val) return lowestCommonAncestor(root.right,p,q);
else if(root.val>p.val&&root.val>q.val) return lowestCommonAncestor(root.left,p,q);
else return root;
}}
2.将两个节点路径的搜索合并到一次调用中
优化后可用于#236.二叉树的最近公共祖先
https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
后续
https://mp.csdn.net/mdeditor/84885524#
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
String[] s = {"",""};
search(root,p,q,"",s);
String route1 = s[0];
String route2 = s[1];
TreeNode node = root;
char[] c1 = route1.toCharArray();
char[] c2 = route2.toCharArray();
int len=c1.length<c2.length?c1.length:c2.length;
for(int i=0;i<len;i++)
{
if(c1[i]==c2[i])
{
if(c1[i]=='1') node=node.left;
else if(c1[i]=='0') node=node.right;
}
else if (c1[i]!=c2[i]) break;
}
return node;
}
private void search(TreeNode root,TreeNode node1,TreeNode node2,String x,String[] s)
{
if(root==null) return ;
if(node1.val==root.val) s[0] = x ;
if(node2.val==root.val) s[1] = x ;
search(root.left,node1,node2,x+"1",s);
search(root.right,node1,node2,x+"0",s);
return;
}
}