1.题目描述
Given a binary tree, return the inorder traversal of its nodes’ values.
给定一个二叉树,返回它的中序 遍历。
Example:
1 | Input: [1,null,2,3] |
Follow up: Recursive solution is trivial, could you do it iteratively?
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
2.Solutions
递归版本
1 | public List<Integer> inorderTraversalWithRecursive(TreeNode root) { |
迭代版本(使用栈)
Explanation
The basic idea is referred from here: using stack to simulate the recursion procedure: for each node, travel to its left child until it’s left leaf, then pop to left leaf’s higher level node A, and switch to A’s right branch. Keep the above steps until cur is null and stack is empty. As the following:
Runtime = O(n): As each node is visited once
Space = O(n)
1 | public List<Integer> inorderTraversal(TreeNode root) { |