Created
June 4, 2017 03:38
-
-
Save jianminchen/d59661bc5b1aee4b72beb792666b206c to your computer and use it in GitHub Desktop.
Leetcode 606 - construct string from binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConstructSTringFromBinaryTree | |
{ | |
public class TreeNode | |
{ | |
public int val; | |
public TreeNode left; | |
public TreeNode right; | |
public TreeNode(int x) { val = x; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
public string Tree2str(TreeNode t) | |
{ | |
if(t == null) | |
{ | |
return string.Empty; | |
} | |
bool leftIsNull = t.left == null; | |
bool rightIsNull = t.right == null; | |
bool noChild = leftIsNull && rightIsNull; | |
if(noChild) | |
{ | |
return t.val.ToString(); | |
} | |
else if(leftIsNull) | |
{ | |
return t.val + "()" + "(" + Tree2str(t.right) + ")"; | |
} | |
else if(rightIsNull) | |
{ | |
return t.val + "(" + Tree2str(t.left) + ")"; | |
} | |
else | |
{ | |
return t.val + "(" + Tree2str(t.left) + ")" + "(" + Tree2str(t.right) + ")"; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment