lintcode 二叉樹的所有路徑
阿新 • • 發佈:2018-11-22
lintcode 二叉樹的所有路徑
每日一練 加油
描述
給一棵二叉樹,找出從根節點到葉子節點的所有路徑。
樣例
給出下面這棵二叉樹:
1
/ \
2 3
\
5
所有根到葉子的路徑為:
[
“1->2->5”,
“1->3”
]
思路:
對於某一個根節點root,他的左右子樹都會分別產生2個路徑的集合vector left 和right 那麼只需要把這兩個集合裡所有的路徑的頭部新增一下root,再把兩個vector合併即可。
空結點和葉節點處理一下就完成了
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: the root of the binary tree * @return: all root-to-leaf paths */ vector<string> binaryTreePaths(TreeNode * root) { // write your code here vector<string> res; if (!root) return res; if (root->left == NULL && root->right == NULL) res.push_back(to_string(root->val)); string head = to_string(root->val); vector<string> left = binaryTreePaths(root->left), right = binaryTreePaths(root->right); for (int i = 0; i < left.size(); i++) left[i] = head + "->" + left[i]; for (int i = 0; i < right.size(); i++) right[i] = head + "->" + right[i]; res.insert(res.end(), left.begin(), left.end()); res.insert(res.end(), right.begin(), right.end()); return res; } };