Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的所有路径 #26

Open
JesseZhao1990 opened this issue Jul 3, 2018 · 0 comments
Open

二叉树的所有路径 #26

JesseZhao1990 opened this issue Jul 3, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

image

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {string[]}
 */
var binaryTreePaths = function(root) {
    var res = [];
    if(root === null) return res;
    if(root.left === null && root.right === null){
        res.push(String(root.val));
        return res;
    }
    
    var leftS = binaryTreePaths(root.left);
    for(var i=0;i<leftS.length;i++){
        res.push(`${root.val}->${leftS[i]}`);
    }
    var rightS = binaryTreePaths(root.right);
    for(var i=0;i<rightS.length;i++){
        res.push(`${root.val}->${rightS[i]}`)
    }
    return res;
    
};

解题思路:递归调用。计算一个节点左子树的字符串数组,和右子树的字符串数组,并和本几点的值串联起来返回。

leetcode原题地址:https://leetcode-cn.com/problems/binary-tree-paths/description/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant