257. Binary Tree Paths(python+cpp)

题目:

Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:

Input:
   1  
 /   \ 
2     3  
 \   
  5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3

解释:
返回二叉树中所有从root到leaf的路径,第一反应就是用dfs做。
python代码:

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

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        result=[]
        def dfs(root,s,result):
            if root.left==None and root.right==None:
                result.append(s)
            if root.left!=None:
                dfs(root.left,s+"->"+str(root.left.val),result)
            if root.right!=None:
                dfs(root.right,s+"->"+str(root.right.val),result)
        if root:
            dfs(root,str(root.val),result)
        return result

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> result;
        if (root)
            dfs(root,to_string(root->val),result);
        return result;
    }
    void dfs(TreeNode* root,string s,vector<string>&result)
    {
        if (root->left==NULL &&root->right==NULL)
            result.push_back(s);
        if (root->left)
            dfs(root->left,s+"->"+to_string(root->left->val),result);
        if(root->right)
            dfs(root->right,s+"->"+to_string(root->right->val),result);
    }
};

总结:
就是很经典的dfs的题目,注意dfs的时候有些判断是无意义的,去掉以后速度会有很明显的提升哦,尽量在进入dfs之前先做好条件判断,因为入栈还要花费一定的时间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值