二叉树中序遍历 binary-tree-inorder-traversal
题目描述
给出一棵二叉树,返回这棵树的中序遍历
例如:
给出的二叉树为{1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵
返回[1,3,2].
备注:递归的解法太没有新意了,你能用迭代的方法来解这道题吗?
如果你不清楚“{1,#,2,3}“的含义的话,请继续阅读
我们用如下方法将二叉树序列化:
二叉树的序列化遵循层序遍历的原则,”#“代表该位置是一条路径的终结,下面不再存在结点。
例如:
1↵ / ↵ 2 3↵ /↵ 4↵ ↵ 5
上述的二叉树序列化的结果是:”{1,2,3,#,#,4,#,#,5}".
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?
confused what"{1,#,2,3}"means?
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}".
解题思路
1.递归解法
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
travel(root, res);
return res;
}
void travel(TreeNode* root, vector<int>& res) {
if(!root) return;
travel(root -> left, res);
res.push_back(root -> val);
travel(root -> right, res);
}
};
2.非递归写法
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s; //保存指向节点的指针
TreeNode* p = root;
while(!s.empty() || p != NULL) {
//左孩子存在,则左孩子入栈
while(p != NULL) {
s.push(p);
p = p -> left;
}
//在栈不空的情况下出栈,并输出出栈节点
if(!s.empty()) {
p = s.top();
s.pop();
res.push_back(p -> val);
p = p -> right;
}
}
return res;
}
};
补充:二叉树先序遍历的非递归写法
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s; //保存指向节点的指针
TreeNode* p;
s.push(root); //根节点入栈
while(!s.empty()) {
p = s.top();
s.pop();
res.push_back(p -> val);
//先入右孩子,如果右孩子存在,则入栈
if(p -> right != NULL) {
s.push(p -> right);
}
//再入左孩子,如果左孩子存在,则入栈
if(p -> left != NULL) {
s.push(p -> left);
}
}
return res;
}
};