Leetcode 606.根據二叉樹創建字符串
阿新 • • 發佈:2019-02-15
left 轉換成 binary 輸入 src 影響 val 宋體 ont
根據二叉樹創建字符串
你需要采用前序遍歷的方式,將一個二叉樹轉換成一個由括號和整數組成的字符串。
空節點則用一對空括號 "()" 表示。而且你需要省略所有不影響字符串與原始二叉樹之間的一對一映射關系的空括號對。
示例 1:
輸入: 二叉樹: [1,2,3,4]
輸出: "1(2(4))(3)"
解釋: 原本將是"1(2(4)())(3())",
在你省略所有不必要的空括號對之後,
它將是"1(2(4))(3)"。
示例 2:
輸入: 二叉樹: [1,2,3,null,4]
輸出: "1(2()(4))(3)"
解釋: 和第一個示例相似,
除了我們不能省略第一個對括號來中斷輸入和輸出之間的一對一映射關系。
思路
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public String tree2str(TreeNode t) { 12 if(t==null) 13 return ""; 14 if(t.left==null && t.right==null) 15 return t.val+""; 16 if(t.right==null) 17 return t.val+"("+tree2str(t.left)+")"; 18 return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")"; 19 } 20 }
Leetcode 606.根據二叉樹創建字符串