Groovy web console

subscribe to the feed Subscribe
to this
TreeNode (via #groovywebconsole)
tweet this snippet Tweet


Published 1 year ago by arshia with tags Closest Common Ancestor (basic)
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
class TreeNode {
    public int value;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val, TreeNode l, TreeNode r) {
        value = val;
        left = l;
        right = r;

public TreeNode ancestor(TreeNode root, int a, int b) {
    if (root == null || root.value == a || root.value == b) {
        return root;
    TreeNode left = ancestor(root.left, a,b);
    TreeNode right = ancestor(root.right, a, b);
    if (left != null && right != null) {
        return root;
    return left == null ? right : left;

TreeNode left2 = new TreeNode(4, null, null);
TreeNode right2 = new TreeNode(5, null, null);
TreeNode left3 = new TreeNode(6, null, null);
TreeNode right3 = new TreeNode(7, null, null);
TreeNode left1 = new TreeNode(2, left2, right2);
TreeNode right1 = new TreeNode(3, left3, right3);
TreeNode root = new TreeNode(1, left1, right1);

println ancestor(root,5,6).value
println "Hello"