Skip to main content

Command Palette

Search for a command to run...

remove half Nodes

Published
1 min readView as Markdown
remove half Nodes
D

I am a Software Engineer currently looking out for jobs around seattle, Washington.

Remove all the half nodes and return the final binary tree.

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

class Solution {
    public TreeNode removeHalfNodes(TreeNode root) {
        if (root == null)
            return null;

        root.left = removeHalfNodes(root.left);
        root.right = removeHalfNodes(root.right);

        if (root.left == null && root.right == null)
            return root;

        if (root.left == null)
            return root.right;

        if (root.right == null)
            return root.left;

        return root;
    }
}

Interview Problems

Part 16 of 17

In this series we will be exploring interview problems asked by various companies. This will be a complete random series and topics will vary from one Data structure to other. Stay tuned!!

Up next

Flipping the Matrix

Given a 2n*2n matrix. You can flip the entire row and entire column as many times as you want, you have to make the first quadrant value maximum after a certain number of operations. Return the sum of the first quadrant after flipping the matrix's co...

More from this blog

Boolean's Blog

27 posts