- 题目
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
-C++
/* follow up: non-recursive version */ class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root == NULL) return res; stack<TreeNode*> s; stack<string> pathStack; s.push(root); pathStack.push(to_string(root->val)); while (!s.empty()) { TreeNode * curNode = s.top(); s.pop(); string tmpPath = pathStack.top(); pathStack.pop(); if (curNode->left == NULL && curNode->right == NULL) { res.push_back(tmpPath); continue; } if (curNode->left != NULL) { s.push(curNode->left); pathStack.push(tmpPath + "->" + to_string(curNode->left->val)); } if (curNode->right != NULL) { s.push(curNode->right); pathStack.push(tmpPath + "->" + to_string(curNode->right->val)); } } return res; } }; //recursive version class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root == NULL) return res; dfs(root, to_string(root->val), res); return res; } void dfs(TreeNode* root, string path, vector<string>& res) { if (root->left == NULL && root->right == NULL) { res.push_back(path); } if (root->left != NULL) dfs(root->left, path + "->" + to_string(root->left->val), res); if (root->right != NULL) dfs(root->right, path + "->" + to_string(root->right->val), res); } };
-python
# dfs + stack def binaryTreePaths1(self, root): if not root: return [] res, stack = [], [(root, "")] while stack: node, ls = stack.pop() if not node.left and not node.right: res.append(ls+str(node.val)) if node.right: stack.append((node.right, ls+str(node.val)+"->")) if node.left: stack.append((node.left, ls+str(node.val)+"->")) return res # bfs + queue def binaryTreePaths2(self, root): if not root: return [] res, queue = [], collections.deque([(root, "")]) while queue: node, ls = queue.popleft() if not node.left and not node.right: res.append(ls+str(node.val)) if node.left: queue.append((node.left, ls+str(node.val)+"->")) if node.right: queue.append((node.right, ls+str(node.val)+"->")) return res # dfs recursively def binaryTreePaths(self, root): if not root: return [] res = [] self.dfs(root, "", res) return res def dfs(self, root, ls, res): if not root.left and not root.right: res.append(ls+str(root.val)) if root.left: self.dfs(root.left, ls+str(root.val)+"->", res) if root.right: self.dfs(root.right, ls+str(root.val)+"->", res)