【题目描述】
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]
.
(1)如果二叉树为空,空操作
(2)如果二叉树不为空,中序遍历左子树,访问根节点,中序遍历右子树
【代码】
递归:
/**
* 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> ans;
vector<int> inorderTraversal(TreeNode* root) {
if(root==NULL) return{};
inorder(root);
return ans;
}
void inorder(TreeNode* root){
if(root==NULL) return;
if(root->left!=NULL) inorder(root->left);
ans.push_back(root->val);
if(root->right!=NULL) inorder(root->right);
}
};
非递归:
/**
* 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> ans;
stack<TreeNode*> s;
if(root==NULL) return {};
TreeNode* node=root;
while(node||!s.empty()){
while(node){
s.push(node);
node=node->left;
}
node=s.top();
s.pop();
ans.push_back(node->val);
node=node->right;
}
return ans;
}
};