Iterative methods: binary tree preorder

Life for the first time about the AC, and there is no reference solution to a problem (though the over-ds content), is to cry dish

 

 1 vector<int> inorderTraversal(TreeNode* root) {
 2     vector<int> res;
 3     stack<TreeNode*> use;
 4     if (!root)
 5         return res;
 6     while (!use.empty()||root)
 7     {
 8         if (root)
 9         {
10             use.push(root);
11             if (root->left)
12                 root = root->left;
13             else
14             {
15                 root = use.top();
16                 use.pop();
17                 res.push_back(root->val);
18                 root = root->right;
19             }
20         }
21         else
22         {
23             root = use.top();
24             use.pop();
25             res.push_back(root->val);
26             root = root->right;
27         }
28     }
29     return res;
30 }

Execution time and memory consumption are above 80%, OK

Guess you like

Origin www.cnblogs.com/zouma/p/11570726.html