1、题目描述:
2、题解:
方法1:递归
Python实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
#递归
if not root:
return []
self.res = []
self.inorder(root)
return self.res
def inorder(self,root):
if not root:
return
self.inorder(root.left)
self.res.append(root.val)
self.inorder(root.right)
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) {
//递归
vector<int> res;
inorder(root,res);
return res;
}
void inorder(TreeNode* root,vector<int>& res){
if (!root){
return;
}
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
};
方法2:迭代:
Python实现:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
#迭代
if not root: return []
stack,res = [],[]
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right
return res
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) {
//迭代
vector<int> res;
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()){
while (root != nullptr){
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
res.push_back(root->val);
root = root->right;
}
return res;
}
};
3、复杂度分析:
时间复杂度:O(N),N为二叉树的结点数,每个节点被访问一次,且只被访问一次。
空间复杂度:O(N),空间复杂度取决于栈深度,而栈深度在二叉树为一条链的情况下会达到 O(n) 的级别。