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].
根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一根结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问,然后按照相同的规则访问其 右子树。因此处理过程如下:
对任一结点p
1.若其左孩子不为空,则将p入栈并将p的左孩子置为当前的p,然后对当前结点p再进行相同的处理;
2.若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将栈顶结点的右孩子置为当前的p
3.直到p为null且栈为空则结束遍历
代码如下:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> vector;
if(!root)
return vector;
stack<TreeNode *> stack;
stack.push(root);
while(!stack.empty())
{
TreeNode *pNode = stack.top();
if(pNode->left)
{
stack.push(pNode->left);
pNode->left = NULL;
}
else
{
vector.push_back(pNode->val);
stack.pop();
if(pNode->right)
stack.push(pNode->right);
}
}
return vector;
}
};
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一根结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问,然后按照相同的规则访问其 右子树。因此处理过程如下:
对任一结点p
1.若其左孩子不为空,则将p入栈并将p的左孩子置为当前的p,然后对当前结点p再进行相同的处理;
2.若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将栈顶结点的右孩子置为当前的p
3.直到p为null且栈为空则结束遍历
代码如下:
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> vector;
if(!root)
return vector;
stack<TreeNode *> stack;
stack.push(root);
while(!stack.empty())
{
TreeNode *pNode = stack.top();
if(pNode->left)
{
stack.push(pNode->left);
pNode->left = NULL;
}
else
{
vector.push_back(pNode->val);
stack.pop();
if(pNode->right)
stack.push(pNode->right);
}
}
return vector;
}
};