Binary Tree Preorder Traversal (非递归实现)

具体思路参见:二叉树的非递归遍历(转)

先序遍历(根左右)。

即把每一个节点当做根节点来对待。

/**
 * 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> res;
        stack<TreeNode*> s;
        while (root!=NULL||!s.empty())
        {
            while (root!=NULL)
            {
                res.push_back(root->val);
                s.push(root);
                root=root->left;
            }
            if(root==NULL)
       { root
=s.top(); root=root->right; s.pop(); } } return res; } };
原文地址:https://www.cnblogs.com/fightformylife/p/4086573.html