题目:
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]
.
解题思路:
直接采用非递归的前序遍历算法求解。
代码:
/** * 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) { vector<int> ans; stack<TreeNode *> st; TreeNode *cur = root; while (cur != NULL || !st.empty()) { if (cur != NULL) { st.push(cur); ans.push_back(cur->val); cur = cur->left; } else { cur = st.top(); st.pop(); cur = cur->right; } } return ans; } };