Same with Inorder.
1. Recursive:
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: A voidGettree (TreeNode *root, vector<int> &result) { - if(!root)return; -Result.push_back (root->val); theGettree (root->Left , result); -Gettree (root->Right , result); - } -vector<int> Preordertraversal (TreeNode *root) { +vector<int>result; - Gettree (root, result); + returnresult; A } at};
2. Directly use stack
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Preordertraversal (TreeNode *root) { -vector<int>result; - if(!root)returnresult; theStack<treenode *>s; - while(Root | |!)S.empty ()) { - if(root) { -S.push (root->Right ); +Result.push_back (root->val); -root = root->Left ; +}Else { ARoot =s.top (); at S.pop (); - } - } - returnresult; - } -};
3. Pointers:
1 /**2 * Definition for binary tree3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Avector<int> Preordertraversal (TreeNode *root) { -vector<int>result; - if(!root)returnresult; theTreeNode *prev =NULL; - while(root) { -Result.push_back (root->val); - if(!root->Left ) { +root = root->Right ; -}Else { +Prev = root->Left ; A while(Prev->right && prev->right! = root) prev = prev->Right ; at if(!prev->Right ) { -Prev->right =Root; -root = root->Left ; -}Else { -Prev->right =NULL; -root = root->Right ; in Result.pop_back (); - } to } + } - returnresult; the } *};
Leetcode–refresh–binary Tree Pre Order traversal