Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
用stack做,res存结果,不要混淆,那么我们要的是res的顺序是preorder, 那么stack是一个缓冲,root, left, right, 那么stack是root, right, left, 用一个while循环来模拟.
This file contains hidden or 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 binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
vector<int> preorderTraversal(TreeNode *root) { | |
vector<int> res; | |
if(root == NULL) return res; | |
stack<TreeNode*> stack; | |
stack.push(root); | |
while(!stack.empty()){ | |
res.push_back(stack.top()->val); | |
TreeNode* tmp = stack.top(); | |
stack.pop(); | |
if(tmp->right) stack.push(tmp->right); | |
if(tmp->left) stack.push(tmp->left); | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment