Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
题目给出了定义好的树结构:
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
这道题的递归解法比较用以想到,但解题会比较慢:
递归实现的代码:
class Solution { //递归方法
public:
vector <int>vec;
void find(TreeNode *root) {
if(root != NULL) {
find(root->left);
vec.push_back(root->val);
find(root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
find(root);
return vec;
}
};
看了大佬的栈实现,受益匪浅,试了一下,果然厉害!题目也说了最好用迭代试一下。迭代的思路,是先找到整棵树最左侧的结点,将一路找到的点都放栈中,然后删掉该点指向左子点的指针(思考一下应该会明白其中的道理)。
class Solution1 //迭代方法
{
public:
Solution1();
~Solution1();
stack<TreeNode*> st;
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if (root != NULL) {
st.push(root);
TreeNode *troot;
while (!st.empty()) { //当栈里还有元素,继续循环
root = st.top();
st.pop();
while (root != NULL) {
troot = root;
root = root->left; //记得要把该点指向左子点的指针置空
troot->left = NULL;
st.push(troot);
}
root = st.top();
st.pop();
ans.push_back(root->val);
//cout << root->val << endl;
root = root->right;
if (root != NULL) {
st.push(root);
}
}
}
return ans;
}
private:
};
结果也很感人!
做完这道题,可以立刻写一下144的前序遍历
class Solution2 {
public:
stack<TreeNode*> st;
map<TreeNode*,int> hash;
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
TreeNode *lr;
if (root) {
st.push(root);
while (!st.empty()) {
root = st.top();
st.pop();
while (root) {
lr = root;
if (!hash[root]) {
ans.push_back(root->val);
cout << root->val << endl;
hash[root] = 1;
}
root = root->left;
lr->left = NULL;
st.push(lr);
}
root = st.top();
st.pop();
if (root->right) {
st.push(root->right);
}
}
}
return ans;
}
};
迭代的力量!!!好强啊!