
Problem Description:
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
2
/
3
return [1,3,2].
题目大意:
中序遍历一个二叉树
Solutions:
用递归的办法做很简单,这里选择一个辅助栈,用非递归的方法完成中序遍历。
Code in C++:
/**
* 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) {
stack<TreeNode*> s;
vector<int> res;
while(!s.empty()||root)
{
s.push(root);
while(root->left)
{
s.push(root->left);
root=root->left;
}
while(!s.empty())
{
root=s.top();
s.pop();
res.push_back(root->val);
if(root->right)
{
root=root->right;
break;
}else root=NULL;
}
}
return res;
}
};




近期评论