题目:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
代码实现:
中序遍历的通用实现可以查看博客:二叉树遍历系列--中序遍历
递归版本:
class Solution { private List<Integer> inorder = new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if (root == null) return inorder; inorderTraversal(root.left); inorder.add(root.val); inorderTraversal(root.right); return inorder; } }
非递归版本:
class Solution { private List<Integer> inorder = new ArrayList<Integer>(); public List<Integer> inorderTraversal(TreeNode root) { if (root == null) return inorder; TreeNode p = root; Stack<TreeNode> stack = new Stack<TreeNode>(); while (p != null) { stack.push(p); p = p.left; while(p == null && !stack.isEmpty()) { p = stack.pop(); inorder.add(p.val); p = p.right; } } return inorder; } }