思路
定义 inorder(root)
表示当前遍历到 root
节点的答案,按照定义,我们只要递归调用 inorder(root.left)
来遍历 root
节点的左子树,然后将 root
节点的值加入答案,再递归调用inorder(root.right)
来遍历 root
节点的右子树即可,递归终止的条件为碰到空节点
解法
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
public void inorder(TreeNode root, List<Integer> res){
if(root == null){
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
- 时间复杂度:
,其中
n
为二叉树节点的个数。二叉树的遍历中每个节点会被访问一次且只会被访问一次 - 空间复杂度:
,空间复杂度取决于递归的栈深度,而栈深度在二叉树为一条链的情况下会达到
的级别