Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 7, 2022 04:05 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To