144. Binary Tree Preorder Traversal
Given a binary tree, return thepreordertraversal of its nodes' values.
For example:
Given binary tree[1,null,2,3],
1
\
2
/
3return[1,2,3].
Thoughts:
Using Stack
Code
/**
* 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:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode *> treeSt;
vector<int> answer;
if(!root) return vector<int>();
treeSt.push(root);
while(!treeSt.empty()){
TreeNode* cur = treeSt.top();
answer.push_back(cur->val);
treeSt.pop();
if(cur->right)treeSt.push(cur->right);
if(cur->left)treeSt.push(cur->left);
}
return answer;
}
};Code 2: Check from the pop
Code (Python)
Previous235. Lowest Common Ancestor of a Binary Search TreeNext255. Verify Preorder Sequence in Binary Search Tree
Last updated
Was this helpful?