题目:https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
题意:二叉树非递归先序遍历
思路:循环终止条件:栈空了
对于二叉树,分成N个小三角来看,先序遍历就是先根再左再右,也就是说根节点先入栈,然后开始循环,栈顶出站,根的数值存起来,右孩子进栈,左孩子近战,然后重复循环即可
代码:
/**
* 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> result;
stack <TreeNode*> stack1;
if(!root) return result;
stack1.push(root);
while(!stack1.empty()){
TreeNode* tmp = stack1.top();
stack1.pop();
result.push_back(tmp->val);
if(tmp -> right){
stack1.push(tmp ->right);
}
if(tmp -> left){
stack1.push(tmp ->left);
}
}
return result;
}
};