题目:
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?
分析:
这道题叫我们实现中序遍历,首先中序遍历就是先左子节点,再是父节点,最后到右子节点的顺序。
因此用到的就是深度优先搜索,用到了栈(stack)的相关知识,这里顺便贴一个科普stack使用的链接,只要知道栈是后进先出就可以啦~
下面贴代码:
/**
* 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;
stack<TreeNode*> nodeStack;
if( root == NULL ){
return res;
}
TreeNode* p = root;
while( p != NULL || !nodeStack.empty() ){
while( p != NULL ){
nodeStack.push(p);
p = p -> left;
}
p = nodeStack.top();
res.push_back(p->val);
nodeStack.pop();
p = p -> right;
}
return res;
}
};