Binary Tree Paths
Given a binary tree, return all root-to-leaf paths.
简单题。考tree的pre-order, 可以recursive 也可以iteration
1) Create an empty stack nodeStack and push root node to stack.
2) Do following while nodeStack is not empty.
….a) Pop an item from stack and print it.
….b) Push right child of popped item to stack
….c) Push left child of popped item to stack
1) Create an empty stack nodeStack and push root node to stack.
2) Do following while nodeStack is not empty.
….a) Pop an item from stack and print it.
….b) Push right child of popped item to stack
….c) Push left child of popped item to stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 preorder(vector<string> &res, string temp, TreeNode* root) { | |
if (!root) { | |
return; | |
} | |
if (!temp.empty()) { | |
temp += "->" + to_string(root->val); | |
} else { | |
temp += to_string(root->val); | |
} | |
if (root->left || root->right) { | |
preorder(res, temp, root->left); | |
preorder(res, temp, root->right); | |
} else { | |
res.push_back(temp); | |
} | |
} | |
vector<string> binaryTreePaths(TreeNode* root) { | |
vector<string> res; | |
string tmp; | |
if (!root) return res; | |
preorder(res, tmp, root); | |
return res; | |
} | |
}; |
No comments:
Post a Comment