题目
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
分析
利用非递归方式实现树的前序遍历。用栈来实现,入栈出栈的规则是:如果当前结点为空,则转去访问栈顶结点的右子树,并使栈顶元素出栈;如果当前结点不为空,则访问当前结点,然后将其压栈,转去访问它的左子树。因为是当前结点->左子树->右子树的顺序,所以遇到结点为空时,一定为左子树为空,而其父节点在栈顶,转去访问父节点的右子树即可。
/**
* 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> preorder;
if (root == NULL) return preorder;
stack<TreeNode*> s;
s.push(root);
preorder.push_back(root->val);
TreeNode* cur = root->left;
while (!s.empty()) {
if (cur == NULL) {
cur = s.top()->right;
s.pop();
if (cur != NULL) {
preorder.push_back(cur->val);
s.push(cur);
cur = cur->left;
}
} else {
preorder.push_back(cur->val);
s.push(cur);
cur = cur->left;
}
}
return preorder;
}
};
>.<