Number of Turns in Binary Tree Solutions
Below code is available in java
class Solution
{
static int NumberOfTurns(Node root, int first, int second)
{
//your code here
List<Node> p1=n2r(root,first);
List<Node> p2=n2r(root,second);
int end1=p1.size()-1;
int end2=p2.size()-1;
while(end1>=0 && end2>=0 ){
if(p1.get(end1)==p2.get(end2)){
end1--;
end2--;
}else{
break;
}
}
end1++;
end2++;
Node LCA=p1.get(end1);
if(LCA.data!=first && LCA.data!=second){
int turn1=getTurns(p1,end1);
int turn2=getTurns(p2,end2);
return turn1+turn2+1;
}else if(LCA.data==first){
int turn=getTurns(p2,end2);
return turn;
}else if(LCA.data==second){
int turn=getTurns(p1,end1);
return turn;
}
return 0;
}
static int getTurns(List<Node> p1,int end1){
StringBuilder sb=new StringBuilder();
for(int i=1;i<=end1;i++){
if(p1.get(i-1)==p1.get(i).right){
sb.append("R");
}else{
sb.append("L");
}
}
int turn=0;
for(int i=1;i<sb.length();i++){
if(sb.charAt(i-1)!=sb.charAt(i)){
turn++;
}
}
return turn;
}
static public List<Node> n2r(Node root,int val){
if(root==null)return new ArrayList<>();
if(root.data==val){
List<Node> base=new ArrayList<>();
base.add(root);
return base;
}
List<Node> left=n2r(root.left,val);
if(left.size() > 0){
left.add(root);
return left;
}
List<Node> right=n2r(root.right,val);
if(right.size() > 0){
right.add(root);
return right;
}
return new ArrayList<>();
}
}
Comments
Post a Comment