606.Construct String from Binary Tree

1- DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public String tree2str(TreeNode t) {
        if(t == null){
            return "";
        }
        else{
            String ans = "";
            ans += t.val;
            String left = "";
            String right = "";
            left = tree2str(t.left);
            right = tree2str(t.right);
            if(t.left != null && t.right != null){
                ans = ans + "(" + left + ")" + "(" + right + ")";
            }
            else if(t.left == null && t.right != null){
                ans = ans + "(" + left + ")" + "(" + right + ")";
            }
            else if(t.left != null && t.right == null){
                ans = ans + "(" + left + ")";
            }
            // if t.left == null && t.right == null, do nothing
            return ans;
        }
    }
}

results matching ""

    No results matching ""