Leetcode 257. 二叉树的所有路径 解题思路及C++实现
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Leetcode 257. 二叉树的所有路径 解题思路及C++实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                解題思路:
使用深度優先搜索(DFS),深度優先搜索的終止條件是:當前節點root為葉子節點,即:!root->left && !root->right 為真,則找到了一條路徑。
/*** 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){if(!root) return {};vector<string> res;dfs(res, root, to_string(root->val));return res;}void dfs(vector<string>& res, TreeNode* root, string tmp){if(!root->left && !root->right){res.push_back(tmp);return;}if(root->left)dfs(res, root->left, tmp + "->" + to_string(root->left->val));if(root->right)dfs(res, root->right, tmp + "->" + to_string(root->right->val));} };?
?
?
總結
以上是生活随笔為你收集整理的Leetcode 257. 二叉树的所有路径 解题思路及C++实现的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: Leetcode 107. 二叉树的层次
 - 下一篇: Leetcode 95. 不同的二叉搜索