Binary Tree Paths

本文介绍了一种算法,用于获取二叉树的所有路径。通过递归方式从根节点到叶子节点进行遍历,并将路径以字符串形式记录下来。提供了C++及Python实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

c++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if (root == nullptr)
            return res;
        getLeafpath(res, root, toString(root->val));
        return res;
    }
private:
    void getLeafpath(vector<string> &res, TreeNode* root, string path) {
        if (root->left == nullptr && root->right == nullptr) {
            res.push_back(path);
            return;
        }
        if(root->left != nullptr)
            getLeafpath(res, root->left, path + "->" + toString(root->left->val));
        if (root->right != nullptr)
            getLeafpath(res, root->right, path + "->" + toString(root->right->val));
    }
    string toString(const int &value) {
        stringstream ss;
        ss << value;
        return ss.str();
    }
};

python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param {TreeNode} root
    # @return {string[]}
    def binaryTreePaths(self, root):
        res = []
        if not root:
            return res
        self.getLeafpath(res, root, str(root.val))
        return res

    def getLeafpath(self, res, root, path):
        if not root.left and not root.right:
            res.append(path)
        if root.left:
            self.getLeafpath(res, root.left, path + '->' + str(root.left.val))
        if root.right:
            self.getLeafpath(res, root.right, path + '->' + str(root.right.val))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值