c# preorder traversal


  • 0
    N
    public class Solution {
        public string Tree2str(TreeNode t) {
            if(t==null) return "";
            return Dfs(t);
        }
        
        public string Dfs(TreeNode t){
            var sb = new StringBuilder();
            sb.Append(t.val);
            if(t.left!=null){
                sb.Append('(');
                sb.Append(Dfs(t.left));
                sb.Append(')');
            }
            if(t.right!=null){
                if(t.left == null){
                    sb.Append("()");
                }
                
                sb.Append('(');
                sb.Append(Dfs(t.right));
                sb.Append(')');
            }
            
            return sb.ToString();
        }
    }
    

Log in to reply
 

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