二叉树的中序遍历
给出一棵二叉树,返回其中序遍历。
样例
给出一棵二叉树 {1,#,2,3},
返回 [1,3,2].挑战
你能使用非递归实现么?
标签
递归 二叉树 二叉树遍历
code
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in vector which contains node values.
*/
public:
vector<int> inorderTraversal(TreeNode *root) {
// write your code here
vector<int> order;
if(root == NULL)
return order;
stack<TreeNode*> s;
TreeNode *p=root;
while(p!=NULL||!s.empty()) {
while(p!=NULL) {
s.push(p);
p=p->left;
}
if(!s.empty()) {
p=s.top();
order.push_back(p->val);
s.pop();
p=p->right;
}
}
return order;
}
};