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

257 二叉树的所有路径 #59

Closed
sailei1 opened this issue Jun 11, 2019 · 0 comments
Closed

257 二叉树的所有路径 #59

sailei1 opened this issue Jun 11, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented Jun 11, 2019

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法:
深度优先遍历

/**
 * 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) {
    if(root==null)
        return [];
    var res=[];
    
    var dfs=function(node,result){
        if(!node){return;}
        if(node.left==null&&node.right==null){
            res.push(result+node.val);
        }
        
        dfs(node.left,result+node.val+'->');
        dfs(node.right,result+node.val+'->');
      
    }
    dfs(root,'');
    return res;
};
@sailei1 sailei1 closed this as completed Jun 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant