力扣刷题日记-606-根据二叉树创建字符串

52 阅读1分钟

思路: 找到规律用递归,主要考虑有左右子树,只有左子树,只有右子树,没有子树的情况,分清楚情况就可以了


/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string}
 */
var tree2str = function(root) {
    const dfs = (root)=> {
        if(root.left && root.right) return `${root.val}(${dfs(root.left)})(${dfs(root.right)})`
        if(root.left && !root.right) return `${root.val}(${dfs(root.left)})`
        if(!root.left && root.right) return `${root.val}()(${dfs(root.right)})`
        if(!root.left && !root.right)return `${root.val}`
    }
    let result = dfs(root)
    return result
};