示例:
1 2 3 4 5 6 7 8
| 输入: [1,null,2,3] 1 \ 2 / 3
输出: [1,3,2]
|
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
本题递归方式很简单,就是标准的框架,我们来看看非递归方式
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { List<Integer> result = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) { inOrder(root); return result; }
void inOrder(TreeNode node) { if (node == null) return;
inOrder(node.left); result.add(node.val); inOrder(node.right); } }
|
要使用非递归方式,肯定需要用栈结构来模拟递归过程。由于中序遍历是左中右顺序,那么可以从根节点开始,一直向左遍历,边遍历边压栈,直到左子树的尽头。这时来处理,将当前节点存进结果数组(即整棵树最左端),然后逆着向上遍历,到父节点,如果有右节点,最后遍历右节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
class Solution { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>();
public List<Integer> inorderTraversal(TreeNode root) { while (root != null || !stack.isEmpty()) { if (root != null) { stack.push(root); root = root.left; } else { root = stack.pop(); result.add(root.val); root = root.right; } } return result; } }
|