Given a binary tree, return the preordertraversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
typedef char ElemType; typedef struct BiTreeNode { ElemType data; struct BiTreeNode *left; struct BiTreeNode *right; }BiTreeNode,*BiTree; Binary Tree Preorder Traversal void TraverseBiTree(BiTree T){ if(T == NULL) return; printf("%c",T->data); TraverseBiTree(T->left); TraverseBiTree(T->right); }
//非递归方法待完善,以下方法便于理解,如果还是不太理解,不妨画图来看一下,见得多了,抽象能力自然就有了。enjoy!
Binary Tree Preorder Traversal 这个方法便于记忆。 class Solution{ public: vector<int> preorderTraversal(TreeNode* root){ if(!root) return {}; vector<int> res; stack<TreeNode*> s{{root}}; while(!s.empty()){ TreeNode* t = s.top();s.pop(); res.push_back(t->val); if(t->right) s.push(t->right); if(t->left) s.push(t->left); } return res; } };
//这个方法可以拓展思路 c++ solution2: class Solution{ public: vector<int> preorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> s; TreeNode *p = root; while(!s.empty() || p){ if(p){ s.push(p); res.push_back(p->val); p = p->left; } else{ TreeNode *t = s.top();s.pop(); p = t->right; } } return res; } };