Java Post Order Traversal(Recursive) Solution


  • 0
    M

    Post order traversal recursive solution:

    class Solution {
        public String tree2str(TreeNode t) {
            if (t == null) return "";
            return helper(t, t);
        }
        
        private String helper (TreeNode t, TreeNode root) {
            if (t == null) return "";
            String left = helper(t.left, root);
            // if left subtree hit leaf but still have nodes at right side,  we need to add an empty "()"
            if (left.equals("") && t.right != null) left += "()";
            String right = helper(t.right, root);
            // if we are parsing the root, root.left and root.right, we don't need to wrap them with "()"
            // else we need to wrap the subtree up with "()"
            return root == t ? t.val + left + right : "(" + t.val + left + right + ")";
        }
        
    }
    

Log in to reply
 

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