Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
給一個二元樹,回傳所有從根到葉的路徑。
注意:葉子是只一個節點沒有任何小孩。
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
root == NULL
)root
的路徑不能有箭號在前面(你也可以在最後不加箭號在後面)
/**
* 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:
void addPath(TreeNode* node, string nowPath, vector<string>& allPath, bool first)
{
if(first)
nowPath += to_string(node->val);
else
nowPath += "->" + to_string(node->val);
if(node->right == NULL && node->left == NULL)
allPath.push_back(nowPath);
if(node->right)
addPath(node->right, nowPath, allPath, false);
if(node->left)
addPath(node->left, nowPath, allPath, false);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> allPath;
if(root)
addPath(root, string(), allPath, true);
return allPath;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up