- Binary Tree Preorder Traversal
中文English
Given a binary tree, return the preorder traversal of its nodes’ values.
Example
Example 1:
Input:{1,2,3}
Output:[1,2,3]
Explanation:
1
/
2 3
it will be serialized {1,2,3}
Preorder traversal
Example 2:
Input:{1,#,2,3}
Output:[1,2,3]
Explanation:
1
2
/
3
it will be serialized {1,#,2,3}
Preorder traversal
Challenge
Can you do it without recursion?
Notice
The first data is the root node, followed by the value of the left and right son nodes, and “#” indicates that there is no child node.
The number of nodes does not exceed 20.
解法1:参考了网上的模板。思路如下:
遍历顺序为根、左、右
- 如果root非空,将root加入到栈中。
- 如果栈不空,弹出出栈顶节点,将其值加加入到数组中。
I. 如果该节点的右子树不为空,将右子节点加入栈中。
II. 如果左子节点不为空,将左子节点加入栈中。 - 重复2), 直到栈空。
注意:
1) 这里的if 都没有else。
2) current=stack.top()后,stack马上就pop(), 与inorder和postorder traversal不一样。
3) 弹出栈顶节点后,先加右节点入栈,再加左节点入栈。
代码如下:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
vector<int> preorderTraversal(TreeNode * root) {
if (!root) return vector<int>();
stack<TreeNode *> s;
vector<int> result;
s.push(root);
while(!s.empty()) {
TreeNode * current = s.top();
result.push_back(current->val);
s.pop();
if (current->right) {
s.push(current->right);
}
if (current->left) {
s.push(current->left);
}
}
return result;
}
};