leetcode257 二叉树的所有路径(未写代码)

1.递归解法

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        if (root == NULL) return res;
        dfs(root, to_string(root->val), res);
        return res;
    }
    
    //搜索root为根的子树,当前路径为path,所有路径结果保存在res里
    void dfs(TreeNode* root, string path, vector<string>& res) {
        if (root->left == NULL && root->right == NULL) {
            res.push_back(path); //到了根节点,则当前path为一种路径,保存到res里
        }
        
        if (root->left != NULL) 
            dfs(root->left, path + "->" + to_string(root->left->val), res); //左子树不为空则搜左边,当前路径加上左子树的根结点值
        
        if (root->right != NULL)
            dfs(root->right, path + "->" + to_string(root->right->val), res);
    }
};

2.DFS using stack

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res; //存放所有路径结果
        TreeNode *curNode;  //当前指向的结点
        string curPath;   //当前节点对应的路径
        stack<pair<TreeNode*, string>> liveNodes; 
        if(root) liveNodes.push(make_pair(root, ""));
        while(!liveNodes.empty())   //类似先序遍历,弹栈入右入左(此处先入左再入右则最终结果路径中最开始的是最右边的路径,不影响)
        {
            curNode = liveNodes.top().first;
            curPath    = liveNodes.top().second; //保存的是从根节点到当前点的路径字符,每个节点都对应一个路径字符串
            liveNodes.pop();  //pop
            if(!curNode->left && !curNode->right)
            {
                res.push_back(curPath + std::to_string(curNode->val));
            }
            else
            {
                if(curNode->left)  liveNodes.push(make_pair(curNode->left, curPath + std::to_string(curNode->val)+ "->"));
                if(curNode->right) liveNodes.push(make_pair(curNode->right, curPath + std::to_string(curNode->val)+ "->")); 
            }
        }
        return res;
    }
};
  1. 层次遍历用队列实现(没细看)

(总结起来就是,用任意一种方式遍历完所有的结点,并保存每个节点所对应的路径,如果是根节点则将该路径保存起来)
参考:
https://leetcode.com/problems/binary-tree-paths/discuss/68536/Three-4ms-c%2B%2B-solutions-given-(recursion-dfs-stack-based-bfs-queue-based)

猜你喜欢

转载自blog.csdn.net/aikudexue/article/details/87994793
今日推荐