Description

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"]

My solution

未能找到合适的解决方案, 实际上还是对stack/遍历/回溯不够熟悉.

Discuss

鉴于上周六去网易有道面试, 问到非递归的中序遍历,我没写出来!!! 所以以后递归和非递归两手抓. ==!

递归

借助helper递归解决问题, 注意递归函数形式(利用stack推出非递归实现方式).

class Solution {
private:
    void helper(TreeNode *root, vector<string> &strvec, string str) {
        if (root->left) helper(root->left, strvec, str + "->" + to_string(root->left->val));
        if (root->right) helper(root->right, strvec, str + "->" + to_string(root->right->val));
        if (!root->left && !root->right) strvec.push_back(str);
    }

public:
    vector<string> binaryTreePaths(TreeNode *root) {
        vector<string> strvec;
        if (!root) return strvec;
        helper(root, strvec, to_string(root->val));
        return strvec;
    }
};

这里的str参数再每次进入下一次递归函数时, 是str+...的形式,也就是传入下层递归函数里面的是"增加过的常量", 如果要用非递归的方式实现,应该增加一个stack<string>,把历史str状态都存放起来.这也就容易理解这里string str而不是string &str了.
这个传入函数str+...的方式和leetcode前面有一道题统计当前节点所在level是一样的实现方式.

迭代

用两个stack分别用作遍历和记录str,因为遍历到底就要有一条str路径形成, 所以这两个stack的push/pop是同步进行的.故也有网友用一个元素为map的stack来实现.
自己重新敲一次 其实很容易理解到, 下面代码就是二叉树的先序遍历非递归方式,并且是最简单的那种方式(不采用类似中序遍历的回溯方法),只不过在遍历的时候,在碰到叶节点时,输出路径.

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode *root) {
        vector<string> res;
        if (root == NULL) return res;
        stack<TreeNode *> s;
        stack<string> pathStack;
        s.push(root);
        pathStack.push(to_string(root->val));

        while (!s.empty()) {
            TreeNode *curNode = s.top();
            s.pop();
            string tmpPath;
            tmpPath = pathStack.top();
            pathStack.pop();

            if (curNode->right) {
                s.push(curNode->right);
                pathStack.push(tmpPath + "->" + to_string(curNode->right->val));
            }
            if (curNode->left) {
                s.push(curNode->left);
                pathStack.push(tmpPath + "->" + to_string(curNode->left->val));
            }
            if (curNode->left && curNode->right) {
                res.push_back(tmpPath);
            }

        }
        return res;
    }
};

Reference


xufeng
8 声望3 粉丝

有多少人工就有多少智能