Binary Tree Inorder Traversal
Binary Tree Inorder Traversal
题目
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].
Note: Recursive solution is trivial, could you do it iteratively?
思路
不断地将当前节点压入到栈中,当前结点等于结点的左结点,直至左结点为NULL。将栈中最顶端的结点的值push_back到result中,当前结点等于最顶端结点的右结点,栈中最顶端结点出栈。 重复上述操作,直至当前节点为空以及栈为空。
解题
c++版
1 | /** |
python版
1 | # Definition for a binary tree node |
c++ 栈版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36/**
* 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> result;
stack<pair<TreeNode*,int>> ss;
ss.push(make_pair(root,0));
while(!ss.empty()){
TreeNode* tmp=ss.top().first;
if(tmp==NULL)
ss.pop();
else{
switch(ss.top().second++){
case 0:
ss.push(make_pair(tmp->left,0));
break;
case 1:
result.push_back(tmp->val);
ss.pop();
ss.push(make_pair(tmp->right,0));
break;
}
}
}
return result;
}
};