中序遍历二叉树
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?
方法一:递归遍历
代码如下:
/**
* 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;
void inorder(TreeNode* root)
{
if(root)
{
inorder(root->left);
res.push_back(root->val);
inorder(root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
res.clear();
inorder(root);
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> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
TreeNode* curr = root;
while(curr != NULL || !stk.empty())
{
while(curr != NULL)
{
stk.push(curr);
curr = curr->left;
}
curr = stk.top(), stk.pop();
res.push_back(curr->val);
curr = curr->right;
}
return res;
}
};
方法三:莫里斯法(线索二叉树)
1、如果当前结点的左孩子为空,则输出当前结点并将当前结点的右结点作为当前结点。
2、如果当前结点的左孩子不为空,则从当前结点的左子树找出当前结点的前驱节点:
如果前驱结点p的右孩子为空,则将p的右孩子设为当前结点;否则,输出当前结点,并将p的右孩子置为空,并将当前当前结点的右孩子置为当前结点
3、重复1 ,2两步直到当前结点为空
/**
* 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;
TreeNode* pre;
while(root != NULL)
{
if(root->left == NULL)
{
res.push_back(root->val);
root = root->right;
}
else
{
pre = root->left;
while(pre->right != NULL && pre->right != root)
{
pre = pre->right;
}
if(pre->right == NULL)
{
pre->right = root;
root = root->left;
}
else
{
pre->right = NULL;
res.push_back(root->val);
root = root->right;
}
}
}
return res;
}
};