LeetCode探索之旅(71)-257二叉树路径

今天继续刷LeetCode,第257题,输出二叉树的所有根节点到叶节点的路径。

分析:
通过深度优先遍历,找到叶子节点(左右孩子都为空),然后输出路径。对于深度优先遍历的时候,就需要用递归。

问题:
1、深度优先遍历中的递归实现;
2、路径保存方法;

附上C++代码1:

class Solution
{
  public:
    vector<string> binaryTreePaths(TreeNode *root)
    {
        vector<string> res;
        if (root == NULL)
            return res;

        if (root->left == NULL && root->right == NULL)
        {
            res.push_back(to_string(root->val));
            return res;
        }
        vector<string> left = binaryTreePaths(root->left);
        for (int i = 0; i < left.size(); i++)
            res.push_back(to_string(root->val) + "->" + left[i]);

        vector<string> right = binaryTreePaths(root->right);
        for (int i = 0; i < right.size(); i++)
            res.push_back(to_string(root->val) + "->" + right[i]);
        return res;
    }
};

附上C++代码2:

/**
 * 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> t;
        if(root==NULL)
            return t;
        string temp=to_string(root->val);
        DFS(root,t,temp);
        return t;
    }
    void DFS(TreeNode * root,vector<string>& t,string temp){
        int index;
        if(!root->left&&!root->right)
        {
            t.push_back(temp);
            return;
        }
        if(root->left)
        {
            temp+="->"+to_string(root->left->val);
            DFS(root->left,t,temp);
            index=temp.rfind("->",temp.size()-1);
            temp.erase(index,temp.size()-index);
        }
        if(root->right)
        {
            temp+="->"+to_string(root->right->val);
            DFS(root->right,t,temp);
            index=temp.rfind("->",temp.size()-1);
            temp.erase(index,temp.size()-index);
        }
    }
};

附上Python代码:

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

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        if not root:
            return []
        res=[]
        self.DFS(root,[],res)
        return res
    
    def DFS(self,root,path,res):
        if root.left is None and root.right is None:
            res.append("".join(path+[str(root.val)]))
            return
        if root.left:
            self.DFS(root.left,path+[str(root.val)+"->"],res)
        if root.right:
            self.DFS(root.right,path+[str(root.val)+"->"],res)

猜你喜欢

转载自blog.csdn.net/JerryZengZ/article/details/89181248