力扣小白刷题之94题二叉树的中序遍历

题目描述

给定一个二叉树,返回它的中序遍历。

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/dong-hua-yan-shi-94-er-cha-shu-de-zhong-xu-bian-li/

递归解法

public static void inOrderRecur(TreeNode head) {
     
	if (head == null) return;
	inOrderRecur(head.left);
	System.out.print(head.value + " ");
	inOrderRecur(head.right);
}

递归实现时,是函数自己调用自己,一层层的嵌套下去,操作系统/虚拟机自动帮我们用 来保存了每个调用的函数。

迭代解法

递归的调用过程是不断往左走,当左边走不下去了,就打印节点,并转向右边,然后右边继续这个过程。我们在迭代实现时,就可以用栈来模拟递归调用过程。
力扣小白刷题之94题二叉树的中序遍历_第1张图片
力扣小白刷题之94题二叉树的中序遍历_第2张图片

力扣小白刷题之94题二叉树的中序遍历_第3张图片
力扣小白刷题之94题二叉树的中序遍历_第4张图片

代码

力扣小白刷题之94题二叉树的中序遍历_第5张图片

时间复杂度:O(n)
空间复杂度:O(h)

你可能感兴趣的:(leetcode)