你需要采用前序遍歷的方式,將一個二叉樹轉換成一個由括號和整數組成的字符串。 空節點則用一對空括號 "()" 表示。而且你需要省略所有不影響字符串與原始二叉樹之間的一對一映射關系的空括號對。 示例 1: 輸入: 二叉樹: [1,2,3,4] 1
/ \ 2 3
/
4 輸出: "1(2(4))(3)" 解釋: 原本將是“1(2(4)())(3())”, 在你省略所有不必要的空括號對之后, 它將是“1(2(4))(3)”。 示例 2: 輸入: 二叉樹: [1,2,3,null,4] 1
/ \ 2 3 \ 4 輸出: "1(2()(4))(3)" 解釋: 和第一個示例相似, 除了我們不能省略第一個對括號來中斷輸入和輸出之間的一對一映射關系。
StringBuilder sb = new StringBuilder(); TreeNode pre = null; public String tree2str(TreeNode t) { if (t == null) return ""; helper(t, pre); return sb.substring(1, sb.length() - 1); } private void helper(TreeNode root, TreeNode pre) { if (root == null) return; //前序遍歷 //1.如果當前節點為父節點的右子樹且左子樹為空,括號不能省略
if (pre != null && pre.left == null && pre.right == root) { sb.append("()"); } sb.append("(").append(root.val); pre = root; helper(root.left, pre); helper(root.right, pre); //遍歷完當前節點后關閉括號
sb.append(")"); }