94.Binary Tree Inorder Traversal
问题概述
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) {}
* };
*/
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;
}
};