[LeetCode] Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
解题思路:
用迭代的方法实现二叉树的遍历,需要借助一些数据结构,比如list,stack等。首先在stack中push入当前的root,由于是前序遍历,故root的value是先于左子树和右子树访问的,故pop取出一个结点,将它的value加入访问序列。之后压入它的右子树和左子树。直到stack为空。
观察这个过程可以发现,每一个node是最先访问的,然后是其左子树,右子树。
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<int> ans; list<TreeNode*> node_list; if(root == NULL) return ans; node_list.push_front(root); while(!node_list.empty()) { TreeNode *cur = node_list.front(); node_list.pop_front(); ans.push_back(cur -> val); if(cur -> right != NULL) node_list.push_front(cur -> right); if(cur -> left != NULL) node_list.push_front(cur -> left); } return ans; } };