Binary Tree forward traversal: the root node is first accessed, followed by left and right subnodes. Iterative versions are also relatively easy to write.
1. Recursive version: time complexity O (N) and space complexity O (N)
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 void dfsPreorderTraversal(TreeNode *root, vector<int> &res) {13 if (root == NULL) {14 return;15 }16 res.push_back(root->val);17 dfsPreorderTraversal(root->left, res);18 dfsPreorderTraversal(root->right, res);19 }20 vector<int> preorderTraversal(TreeNode *root) {21 vector<int> res;22 dfsPreorderTraversal(root, res);23 return res;24 }25 };
Conclusion: Ce once, the vector type definition is incorrect.
2. Iterative version: time complexity O (N) and space complexity O (N)
/*** 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) {stack <treenode *> S; // s stores the sequence of treenodes vector <int> res; // res stores the result s. push (Root); While (! S. Empty () {treenode * Now = S. Top (); // What is the difference in program efficiency if now is defined outside the loop? S. Pop (); If (now! = NULL) {res. push_back (now-> Val); S. push (now-> right); S. push (now-> left) ;}} return res ;}};
Summary: times... Stack usage is always forgotten... It is actually push, pop, and top.
3. What is the preorder traversal of Morris?
Wait for further research if necessary.
4. What are the essential differences between Recursion and iteration?
Iteration is essentially a process of simulating recursion, which avoids multiple program calls and is more efficient.