Four lines of Java code (Recursion - Simple)


  • 0
    N

    If we see the pattern(s) of input array (containing null elements), all has to be taken care of is that empty paranthesis "()" is returned only when left child is null and right child is non-empty. The following are details of each condition:

    • If current node is null, then return empty string.
    • If right child is not null, then traverse to both children regardless of left child's reference (null or anything).
    • If right child is null, then navigate only to left child (since "()" is not required for right child's null value).
    • If both children are null return current node's value.

    Now if you read the following code and test run, it will be clear.

    public class Solution {
        public String tree2str(TreeNode t) {
            if(t==null) return "";
            if(t.right!=null) return t.val + "(" + tree2str(t.left) + ")(" + tree2str(t.right)+")";
            if(t.left!=null && t.right==null) return t.val + "(" + tree2str(t.left) + ")";
            return String.valueOf(t.val);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.