具体思路参见:二叉树的非递归遍历(转)
/** * 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; } };
时间: 2024-11-05 20:29:48