(JS栈) LeetCode257. 二叉树的所有路径

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

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

示例:
输入:

   1
 /   \
2     3
 \
  5

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

方法一 递归
思路:
1、在当前路径追加当前节点值;
2、如果该节点是叶子节点,则添加到结果数组;
3、如果不是,递归处理该节点的子节点,并传入当前path值;
时间复杂度:O(n)
空间复杂度:O(n)

var binaryTreePaths = function(root) {
    let path = '';
    let res = [];
    let helper = (root, path) => {
        if(!root) return;
        path += String(root.val);
        if(root.left === null && root.right === null){
            res.push(path)
        }else{
            path += '->'
            helper(root.left, path)
            helper(root.right, path)
        }
    }
    helper(root, '')
    return res;
};

方法二 广度优先遍历

思路:
1、维护一个栈,存储节点以及根到该节点的路径。
2、在每一步迭代中,我们取出队列中的首节点。
(1)如果它是一个叶子节点,则将它对应的路径加入到答案中。
(2)如果它不是一个叶子节点,则将它的所有孩子节点加入到队列的末尾。
3、当队列为空时,迭代结束。
时间复杂度:O(n)
空间复杂度:O(n)

let binaryTreePaths = (root) => {
    let node;
    let path;
    let paths = [];
    if (root == null)
        return paths;

    let node_stack = [];
    let path_stack = [];

    node_stack.push(root);
    path_stack.push(String(root.val));
    
    while (!!node_stack.length) {
        node = node_stack.pop();
        path = path_stack.pop();
        if ((node.left == null) && (node.right == null))
            paths.push(path);

        if (node.left != null) {
            node_stack.push(node.left);
            path_stack.push(path + "->" + String(node.left.val));
        }
        if (node.right != null) {
            node_stack.push(node.right);
            path_stack.push(path + "->" + String(node.right.val));
        }
    }
    return paths;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容