中序遍历定义
首先遍历左子树,然后访问根结点,最后遍历右子树。
遵循:左根右
如图所示:中序遍历结果为4 2 5 1 3
解释图:
leetcode 94.二叉树的中序遍历
法一:利用栈
/**
* 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> res;
if(!root)
return res;
stack<TreeNode*> st;
TreeNode* node = root;
while(1){
while(node){//进入左子树
st.push(node);
node = node->left;
}
if(st.empty())//若为空,则遍历完所有的结点
break;
node = st.top();
st.pop();
res.push_back(node->val);//将结点值放入数组
node = node->right;//进入右子树
}
return res;
}
};
法二:递归
/**
* 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> res;//注意放在外面
vector<int> inorderTraversal(TreeNode* root) {
if(root!=NULL){
inorderTraversal(root->left);//沿左子树向下走
res.push_back(root->val);
inorderTraversal(root->right);
}
return res;
}
};