257. Binary Tree Paths(DFS)

来源:互联网 发布:商城html源码下载 编辑:程序博客网 时间:2024/06/05 10:46

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

2. Analysis

既然是二叉树,自然就会想到二叉树遍历算法,采用先序遍历的思想,从左到右遍历每个叶结点。需要注意的是,当跑到第一个叶节点,并记录第一条路径后,如何能跑到第二个叶节点,找到第二条路径,因为这条路径(String表示)的前部分是相同的,一开始我直接使用引用传参了,然而很明显这是不对的,后来改成了值引用,在递归的过程保存结果,开销大了些,结果是正确的。


3. Algorithm achievement

/** * 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:    /*int 转 string*/    static string toString(const int num) {        stringstream transfer;        transfer << num;        return transfer.str();    }    static void recursizeBTP(TreeNode* root, string ans, vector<string>& res) {        if(root == NULL) return;        ans += toString(root->val);        /*非根结点需要加连接符号—>*/        if(root->left != NULL || root->right != NULL )            ans += "->";        /*到达根结点*/        if(root->left == NULL && root->right == NULL) {            res.push_back(ans);            return;        }        recursizeBTP(root->left, ans, res);        recursizeBTP(root->right, ans, res);        return;    }    vector<string> binaryTreePaths(TreeNode* root) {        if(root == NULL) return {};         vector<string> res;        string ans = toString(root->val);        /*整棵树只有根结点的情况*/        if(root->left == NULL && root->right == NULL ) {            res.push_back(ans);            return res;        }        /*不仅根结点,就需要加上连接符号->*/        if(root->left != NULL || root->right != NULL)            ans += "->";        TreeNode * node = root;        if(root->left != NULL) {            recursizeBTP(root->left, ans, res);        }        if(root->right != NULL) {            recursizeBTP(root->right, ans, res);        }        return res;    }};