问题描述
地址:https://leetcode.com/problems/binary-tree-inorder-traversal/
描述:
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
翻译:
给出一个二叉树,返回中序遍历的节点值。
注意:尽量使用迭代,尽量不用递归。
问题解析
这个题目是非常常见的二叉树的遍历问题。常见的二叉树遍历有四种:先序遍历,中序遍历,后序遍历,层次遍历。
所谓的先序、中序和后续遍历二叉树,思想一致,只不过打印节点的时机不一样而已。
下面以下图中的树为例解析:
步骤1-2:
步骤3-4:
解析代码
(1)非递归
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode treeNode = stack.pop();
result.add(treeNode.val);
root = treeNode.right;
}
return result;
}
(2)递归
List<Integer> result = new ArrayList<Integer>();
public List<Integer> inorderTraversalRecursion(TreeNode root) {
if (root == null) {
return result;
}
inorderTraversalRecursion(root.left);
result.add(root.val);
inorderTraversalRecursion(root.right);
return result;
}