2-liner Python and 3-liner C++ O(N) pre-order traversal


  • 0

    Whether to wrap a node value with brackets:

    • Wrap a left node iff either left or right nodes are not NULL;
    • Wrap a right node iff right node is not NULL.

    Note: do NOT wrap root.

    string tree2str(TreeNode* t, bool wrap = false) {
            return (wrap? "(" : "") 
                 + (t? to_string(t->val) + tree2str(t->left, t->left||t->right) + tree2str(t->right, t->right) : "")
                 + (wrap? ")" : "");
        }
    

    Python

        def tree2str(self, t, wrap = False):
            s = '(%s)' %(str(t.val) + self.tree2str(t.left, t.left or t.right) + self.tree2str(t.right, t.right)) if t else '()'
            return s if wrap else s[1:-1]
    

Log in to reply
 

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