中序遍历:即先遍历左子树节点,再遍历根节点,再遍历右子树节点
例如:
上图中序遍历的结果是:CBDAE
有两种方式
1 、递归(自己调用自己)
// 递归
List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return result;
TreeNode left = root.left;
if (left!=null) {
result = inorderTraversal(left);
}
result.add(root.val);
TreeNode right = root.right;
if (right!=null) {
result = inorderTraversal(right);
}
return result;
}
2、迭代器(使用栈)
/*迭代*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
if(root == null) return result;
Stack<TreeNode> stack = new Stack<>();
TreeNode ctr = root;
while (stack.size() > 0 || ctr != null) {
// 遍历左侧分支
while (ctr != null) {
stack.push(ctr);
ctr = ctr.left;
}
TreeNode node = stack.peek();
stack.pop();
result.add(node.val);
ctr = node.right;
}
return result;
}