lintcode-二叉树的前序遍历(非递归)-66

给出一棵二叉树,返回其节点值的前序遍历。

样例

给出一棵二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

 返回 [1,2,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:
   
    vector<int> preorderTraversal(TreeNode *root) {
        stack<TreeNode*> s;
        TreeNode *cur=root;
        vector<int> ret;
        
        while(cur||!s.empty()){
            if(cur){
                ret.push_back(cur->val);
                s.push(cur);
                cur=cur->left;
            }else{
                cur=s.top();
                s.pop();
                cur=cur->right;
            }
        }
        return ret;
    }
};


你可能感兴趣的:(lintcode-二叉树的前序遍历(非递归)-66)