An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
September 7, 2022 04:05 am GMT
Original Link: https://dev.to/salahelhossiny/construct-string-from-binary-tree-34n6
Construct String from Binary Tree
Given the root of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public String tree2str(TreeNode t) { if(t==null) return ""; if(t.left==null && t.right==null) return t.val+""; if(t.right==null) return t.val+"("+tree2str(t.left)+")"; return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")"; }}
Original Link: https://dev.to/salahelhossiny/construct-string-from-binary-tree-34n6
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To