94. Binary Tree Inorder Traversal
Description:
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(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
recur(root, res);
return res;
}
void recur(TreeNode *root, vector<int> & res){
if(root){
recur(root->left, res);
res.push_back(root->val);
recur(root->right, res);
}
}
};
第二种思路使用非递归方式,从二叉树根节点开始,搜索左子节点以及其左子节点直到某一节点的左节点为空时将此节点值压栈,再搜索此节点的右节点,再用同样方式访问该右节点的子节点。
代码如下:
/**
* 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> res;
stack<TreeNode*> s;
while(root || !s.empty()){
if(root) {
s.push(root);
root = root->left;
} else {
root = s.top();
res.push_back(root->val);
s.pop();
root = root->right;
}
}
return res;
}
};