ITPub博客

首页 > > > [LeetCode] Binary Tree Paths

[LeetCode] Binary Tree Paths

作者:Ruiyuan Li 时间:2015-08-17 00:00:00 0 删除 编辑

Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

解题思路:

这道题题意是返回二叉树中所有从根到叶的路径。用递归法做比较方便。

/**
 * 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 binaryTreePaths(TreeNode* root) {
        vector result;
        helper(root, "", result);
        return result;
    }
    
    void helper(TreeNode* root, string item, vector& result){
        if(root==NULL){
            return;
        }
        item = item+std::to_string(root->val);
        if(root->left!=NULL){
            helper(root->left, item + "->", result);
        }
        if(root->right!=NULL){
            helper(root->right, item + "->", result);
        }
        if(root->left==NULL&&root->right==NULL){
            result.push_back(item);
        }
    }
};


转载请注明: » [LeetCode] Binary Tree Paths
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

下一篇: c# 汉字转拼音
请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4825