- Binary Tree Inorder Traversal(easy)
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
/**
* 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) {}
* };
*/
中序遍历的实现方式:访问完左子树,再访问根节点,最后访问右子树。
- 递归
递归的程序很简单,此处不提 - 迭代1
使用栈,循环不嵌套。树节点cur指向根节点,cur不为空或者stack不为空,迭代继续。如果cur不为空,cur入栈,继续访问cur的左孩子cur=cur->left。如果cur为空,cur=栈顶元素,将cur->val保存到res数组中,cur=cur->right.
由中序遍历的定义可知,遍历到一个节点时(输出),其左子树已经被遍历完毕(对应程序,此时cur=null,说明在当前子树上已经遍历完毕),开始遍历其右子树(cur=cur->right)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
if(!root){
return res;
}
TreeNode *cur=root;
stack<TreeNode*>s;
while(cur||!s.empty()){
if(cur){
s.push(cur);
cur=cur->left;
}else{
cur=s.top();
s.pop();
res.push_back(cur->val);
cur=cur->right;
}
}
return res;
}
};
- 迭代
cur指向当前节点,cur!=null时,将cur入栈,cur下沉到cur的左孩子。cur=null时,弹出栈顶元素,输出,cur下沉到cur的右孩子。
vector<int> inorderTraversal(TreeNode* root) {
vector<int>res;
stack<TreeNode*>s;
TreeNode* cur=root;
while(cur||!s.empty()){
while(cur){
s.push(cur);
cur=cur->left;
}
cur=s.top();
s.pop();
res.push_back(cur->val);
cur=cur->right;
}
return res;
}