94-中序遍历二叉树
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]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
solution from discuss:
递归解法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
helper(root,res);
return res;
}
void helper(TreeNode* root, vector<int> &res){//注意这里&res,传参的
if(root != NULL){
helper(root->left,res);
res.push_back(root->val);
helper(root->right,res);
}
}
};
迭代,非递归解法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
TreeNode *node=root;
while(!s.empty() || node){//栈不为空或者当前node不为空
while(node){
s.push(node);
node=node->left;
}
node=s.top();
s.pop();
res.push_back(node->val);//加入答案中
node=node->right;//????????不懂
}
return res;
}
};
以只有三个节点的树为例。
A先入栈,B后入栈。B没有左子树了,跳出入栈的while循环。
后面弹出B,B的值先放入res中。然后node此时是B->right, 也就是NULL
再次while循环时,不会进入栈的循环,直接弹栈,弹出A,A的值进入res,A有右节点,此时指向node=C
再次while循环,C会入栈,后面接着弹栈,弹出C。
(要想访问右节点,必然是在当前父节点加入res之后进行的,保证了根在右之前访问。
而入栈顺序保证了先访问左节点)