C# Solution


  • 0
    public class Solution {
        public string Tree2str(TreeNode t) {
            if (t == null)
                return string.Empty;
            else if (t.left == null && t.right == null)
                return t.val.ToString();
            
            StringBuilder result = new StringBuilder();
            
            result.Append(t.val.ToString());
            if (t.right != null)
            {
                ExtendResult(t.left, result);
                ExtendResult(t.right, result);
            }
            else if (t.left != null)
                ExtendResult(t.left, result);
            
            return result.ToString();
        }
        
        private StringBuilder ExtendResult(TreeNode node, StringBuilder lastLevel)
        {
            lastLevel.Append("(");
            
            if (node != null)
            {
                lastLevel.Append(node.val);
                
                if (node.right != null)
                {
                    ExtendResult(node.left, lastLevel);
                    ExtendResult(node.right, lastLevel);
                }
                else if (node.left != null)
                    ExtendResult(node.left, lastLevel);
            }
            
            lastLevel.Append(")");
            
            return lastLevel;
        }
    }

Log in to reply
 

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