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
/
3
return[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
/**
* 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) {
vector<int> answer;
// if(!root) return answer;
stack<TreeNode *> treeSt;
treeSt.push(root);
while(!treeSt.empty()){
TreeNode* cur = treeSt.top();
treeSt.pop();
if (cur){
answer.push_back(cur ->val);
treeSt.push(cur->right);
treeSt.push(cur->left);
}
}
return answer;
}
};
Code (Python)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
stack, res = [root], []
while stack:
node = stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res