给定一个二叉树,返回它的中序 遍历。
输入: [1,null,2,3]
输出: [1,3,2]
【递归】
List<Integer> res = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
inorder(root);
return res;
}
private void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
res.add(root.val);
inorder(root.right);
}
【迭代】
List<Integer> res = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()){
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
res.add(root.val);
root = root.right;
}
return res;
}