问题:
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]
.
分析:
二叉树的中序遍历顺序为左-根-右,可用递归来做:
对左子结点调用递归函数,根节点访问值,右子节点再调用递归函数
代码:
/**
* 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;
intrav(root,res);
return res;
}
void intrav(TreeNode* root,vector<int>& res){
if(!root) return;
//左-根-右
if(root->left) intrav(root->left,res);
res.push_back(root->val);
if(root->right) intrav(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> result;
stack<TreeNode*> s;
TreeNode* p=root;
while(p||!s.empty()){
//左
if(p){
s.push(p);
p=p->left;
}else{
p=s.top();
s.pop();
//根
result.push_back(p->val);
//右
p=p->right;
}
}
return result;
}
};