二叉树 - 二叉树的所有路径

257. 二叉树的所有路径

在这里插入图片描述

在这里插入图片描述

方法一:递归法:

/**
 * 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 binaryTreePaths = function (root) {
    // 递归遍历 + 递归三部曲
    let res = [];
    // 1. 确定递归函数 函数参数
    const getPath = function(node, curPath) {
        //2. 确定终止条件,到叶子节点就终止
        if (node.left === null && node.right === null) {
            curPath += node.val;
            res.push(curPath);
            return;
        }
        // 3. 确定单层递归逻辑
        curPath += node.val + '->';
        node.left && getPath(node.left, curPath);
        node.right && getPath(node.right, curPath);
    }
    getPath(root, '');
    return res;
};

方法二:迭代法:

/**
 * 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 binaryTreePaths = function (root) {
    if (!root) return [];
    const stack = [root], paths = [''], res = [];
    while (stack.length) {
        const node = stack.pop();
        let path = paths.pop();
        if (!node.left && !node.right) {  // 到叶子节点终止,添加路径到结果中
            res.push(path + node.val);
            continue;
        }
        path += node.val + '->';
        if (node.right) {  // 右节点存在
            stack.push(node.right);
            paths.push(path);
        }
        if (node.left) {  // 左节点存在
            stack.push(node.left);
            paths.push(path);
        }
    }
    return res;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值