这道题用递归很好做,都不知道该怎么描述,这里就直接贴递归代码了,迭代的做法稍微讲一下。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> result;
vector<int> inorderTraversal(TreeNode* root) {
if(root){
inorderTraversal(root -> left);
result.emplace_back(root -> val);
inorderTraversal(root -> right);
}
return result;
}
};
感觉二叉树的迭代遍历一定会用到队列或者栈,这里主要用的是栈。我们从根节点出发,用一个while
循环不断向左遍历,并将遍历到的节点压入栈中,当遇到空节点时,此时的栈顶元素为空节点的父节点,此时我们再从栈顶的节点出发,对栈顶节点的右孩子进行相同的遍历操作(不断向左遍历),并将遍历到的节点也加入到栈中。当右孩子也为空时,此时栈顶元素为当前节点的祖父节点,同样直接弹出栈顶元素,并将其加入到向量中。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
while(!st.empty() || root){
if(root){ //当前遍历到的节点不为空
st.push(root);
root = root -> left;
}
else{ //栈顶节点的左孩子为空
root = st.top();
result.emplace_back(root -> val);
st.pop(); //将已经存入数组的节点弹出
root = root -> right;
}
}
return result;
}
};