
正文
【LeetCode】94. Binary Tree Inorder Traversal
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
题目:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
{1,#,2,3}
,
1
\
2
/
3
return
[1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/ \
2 3
/
4
\
5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.
提示:
题目要求给出二叉树的中序遍历,总共有三种方法可以使用:
- 函数递归
- 利用Stack迭代
- Morris遍历法
其中递归法比较简单,这里就不赘述了。下面的代码部分主要贴出第二和第三种方法,其中关于Morris遍历法的解释,可以点击链接查看。
代码:
首先是利用Stack迭代:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> result;
stack<TreeNode *> stack;
TreeNode *pCurrent = root;
while(!stack.empty() || pCurrent)
{
if(pCurrent)
{
stack.push(pCurrent);
pCurrent = pCurrent->left;
}
else
{
TreeNode *pNode = stack.top();
result.push_back(pNode->val);
stack.pop();
pCurrent = pNode->right;
}
}
return result;
}
};
然后是使用Morris遍历:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode *cur = root, *prev = NULL;
while (cur != NULL) {
if (cur->left == NULL) {
result.push_back(cur->val);
cur = cur->right;
} else {
prev = cur->left;
while(prev->right != NULL && prev->right != cur)
prev = prev->right; if (prev->right == NULL) {
prev->right = cur;
cur = cur->left;
} else {
prev->right = NULL;
result.push_back(cur->val);
cur = cur->right;
}
}
}
return result;
}
};







