Skip to content

Instantly share code, notes, and snippets.

@summit87
Created October 20, 2019 23:33
Show Gist options
  • Select an option

  • Save summit87/fb90bc710388183a69f4231f94b86811 to your computer and use it in GitHub Desktop.

Select an option

Save summit87/fb90bc710388183a69f4231f94b86811 to your computer and use it in GitHub Desktop.
package com.practice.backtracking.tree;
public class MaxConsecutiveLength {
public static void main(String[] args) {
BT bt = new BT(10);
bt.setLeft(new BT(1));
bt.setRight(new BT(9));
bt.getLeft().setLeft(new BT(13));
bt.getLeft().setRight(new BT(12));
bt.getLeft().getRight().setLeft(new BT(13));
bt.getRight().setLeft(new BT(13));
bt.getRight().setRight(new BT(18));
BT bt1 = new BT(5);
bt1.setLeft(new BT(8));
bt1.getLeft().setLeft(new BT(9));
bt1.getLeft().getLeft().setLeft(new BT(13));
bt1.setRight(new BT(11));
bt1.getRight().setRight(new BT(10));
bt1.getRight().getRight().setLeft(new BT(9));
System.out.println(maxLen(bt, 1, 1) + 1);// including 1 bcz of each node
}
private static int maxLen(BT bt, int ls, int rs) {
if (bt == null) {
return 0;
}
if (bt.getLeft() != null && bt.getData() + 1 == bt.getLeft().getData()) {
return 1 + maxLen(bt.getLeft(), ls, rs);
}
if (bt.getRight() != null && bt.getData() + 1 == bt.getRight().getData()) {
return 1 + maxLen(bt.getRight(), ls, rs);
}
return Math.max(maxLen(bt.getRight(), ls, rs), maxLen(bt.getLeft(), ls, rs));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment