Binary Tree Paths - 二叉树路径

2016-11-03  本文已影响54人  郑明明
vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        vector<int> path;
        BFS (root, result, path);
        return result;
    }
    
    void BFS (TreeNode *treeNode, vector<string> &result, vector<int> &path) {
        if (treeNode == NULL) {
            return;
        }
        path.push_back(treeNode->val);
        if (treeNode->left == NULL && treeNode->right == NULL) {
            result.push_back(generatePath(path));
        }
        if (treeNode->left != NULL) {
            BFS (treeNode->left, result, path);
            path.pop_back(); // 这里对path进行弹栈,导致path复用,思路真是精妙
        }
        if (treeNode->right != NULL) {
            BFS (treeNode->right, result, path);
            path.pop_back();
        }
    }
    
    string generatePath(vector<int> path) {
        stringstream ss;
        int i;
        for (i = 0; i < path.size() - 1; i++) ss << path[i] << "->";
        ss << path[i];
        return ss.str();
    }
上一篇下一篇

猜你喜欢

热点阅读