题目
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: 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;
if(root==NULL)
return res;
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
return res;
}
void inorder(TreeNode* r,vector<int>& v)
{
if(r==NULL)
return;
inorder(r->left,v);
v.push_back(r->val);
inorder(r->right,v);
}
};
迭代法:
/**
* 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*> inorder;//迭代法需要的栈
if(root==NULL)
return res;
inorder.push(root);//先压入根节点
TreeNode* r=root->left;//r指向左子树
while(!inorder.empty())//如果栈非空
{
if(r!=NULL)//r不为NULL,则将r入栈,继续沿左子树遍历
{
inorder.push(r);
r=r->left;
}
else//当r为NULL时
{
r=inorder.top();//弹出栈顶元素
inorder.pop();
res.push_back(r->val);//将值压入向量,进行中根遍历
r=r->right;//指向右子树
if(r!=NULL)//如果右子树不为NULL
{
inorder.push(r);//将右子树入栈
r=r->left;//沿右子树的左子树继续遍历
}
}
}
return res;
}
};