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?
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
TreeNode* p=root;
stack<TreeNode*> nodeStack;
while(!nodeStack.empty() || p!=NULL){
if(p!=NULL){
nodeStack.push(p);
p=p->left;
}else{
result.push_back(nodeStack.top()->val);
p=nodeStack.top();
nodeStack.pop();
p=p->right;
}
}
return result;
}
};
思路心得:
中序遍历获前序遍历其实在非递归实现的方法是非常相似的,只是遍历结点的时机不同。
【LeetCode】144. Binary Tree Preorder Traversal
中序遍历的遍历时机为出栈时,前序为入栈时。所以同一个遍历序列可组成的树的数和出栈顺序数同符合卡特兰数的规则的原因就是因为他俩的本质其实非常接近
【LeetCode】96. Unique Binary Search Trees