Problem
You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.
The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don"t affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: Binary tree: [1,2,3,4]
1 / 2 3 / 4
Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())",
but you need to omit all the unnecessary empty parenthesis pairs.
And it will be "1(2(4))(3)".
Example 2:
Input: Binary tree: [1,2,3,null,4]
1 / 2 3 4
Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example,
except we can"t omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
class Solution { public String tree2str(TreeNode t) { if (t == null) return ""; String str = String.valueOf(t.val); if (t.left != null) { str += "(" + tree2str(t.left) + ")"; } if (t.right != null) { if (t.left == null) str += "()"; str += "(" + tree2str(t.right) + ")"; } return str; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/72110.html
摘要:題意從一顆二叉樹轉為帶括號的字符串。這題是的姊妹題型,該題目的解法在這里解法。 LeetCode 606. Construct String from Binary Tree You need to construct a string consists of parenthesis and integers from a binary tree with the preorder t...
摘要:在線網站地址我的微信公眾號完整題目列表從年月日起,每天更新一題,順序從易到難,目前已更新個題。這是項目地址歡迎一起交流學習。 這篇文章記錄我練習的 LeetCode 題目,語言 JavaScript。 在線網站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公眾號: showImg(htt...
摘要:題意從一個帶括號的字符串,構建一顆二叉樹。其中當而時,展示為一個空的括號。同時要考慮負數的情況,所以在取數字的時候,必須注意所在位置。遇到則從棧中出元素。最后中的元素就是,返回棧頂元素即可。 LeetCode 536. Construct Binary Tree from String You need to construct a binary tree from a string ...
摘要:做了幾道二分法的題目練手,發現這道題已經淡忘了,記錄一下。這道題目的要點在于找的區間。邊界條件需要注意若或數組為空,返回空當前進到超出末位,或超過,返回空每次創建完根節點之后,要將加,才能進行遞歸。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...
摘要:二分法復雜度時間空間思路我們先考察先序遍歷序列和中序遍歷序列的特點。對于中序遍歷序列,根在中間部分,從根的地方分割,前半部分是根的左子樹,后半部分是根的右子樹。 Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a tree, constru...
閱讀 2430·2019-08-29 13:53
閱讀 2512·2019-08-29 11:32
閱讀 3053·2019-08-28 17:51
閱讀 3787·2019-08-26 10:45
閱讀 3514·2019-08-23 17:51
閱讀 2986·2019-08-23 16:56
閱讀 3340·2019-08-23 16:25
閱讀 3093·2019-08-23 14:15