首页 > 代码库 > Binary Tree Preorder Traversal (非递归实现)

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; }};

 

Binary Tree Preorder Traversal (非递归实现)