Binary Tree Inorder Traversal My Submissions Question Solution Total
Accepted: 85535 Total Submissions: 232962 Difficulty: Medium 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?
confused what “{1,#,2,3}” means? > read more on how binary tree is
serialized on OJ.
二叉树的中序遍历
递归的方法
/**
* 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> v;
recur_inorder(root,v);
return v;
}
void recur_inorder(TreeNode* T, vector<int> &v){
if(T!=NULL){
if(T->left!=NULL)
recur_inorder(T->left,v);
v.push_back(T->val);
if(T->right!=NULL)
recur_inorder(T->right,v);
}
}
};
非递归使用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) {
stack<TreeNode*> sta;
vector<int> v;
TreeNode* T= root;
// sta.push(T);
while(!sta.empty()||T){
while(T!=NULL){
sta.push(T);
T= T->left;
}
T= sta.top();
sta.pop();
v.push_back(T->val);
T = T->right;
}
return v;
}
};
Morris Traversal方法遍历二叉树(非递归,不用栈,O(1)空间)
这里要重点讲的方法