【题目描述】
【思路一递归】
递归解决,对左子递归,将中子打印,而后将右子递归。
python:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
self.re=[]
self.dfs(root)
return self.re
def dfs(self,root):
if root:
self.dfs(root.left)
self.re.append(root.val)
self.dfs(root.right)
c++:
class Solution {
public:
vector<int> re;
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return re;
}
void dfs(TreeNode* root){
if(root){
dfs(root->left);
re.push_back(root->val);
dfs(root->right);
}
}
};
时间复杂度O(n),空间复杂度来自于递归栈,与树高有关,最坏O(n).
【思路二迭代】
迭代,利用栈。
起初的当前节cur点为根节点,进入while循环, 1)只要cur存在,就入栈,并更新cur为cur.left;
2)若cur不存在,代表着当前栈顶节点top没有左子节点,可以令top出栈,然后top.right入栈。
python:
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
re=[]
stack=[]
cur=root
while stack or cur:
if cur:
stack.append(cur)
cur=cur.left
else:
cur=stack.pop()
re.append(cur.val)
cur=cur.right
return re
C++:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> re;
stack<TreeNode*> stack;
TreeNode* cur=root;
while (cur || !stack.empty()){
if(cur){
stack.push(cur);
cur=cur->left;
}
else{
cur=stack.top();
stack.pop();
re.push_back(cur->val);
cur=cur->right;
}
}
return re;
}
};
时间复杂度O(n),空间复杂度来自栈,每个节点都会入栈一次,因此为O(n).