题目
题源
略
代码
递归法:
class Solution {
List<Integer> list = new LinkedList<>();
public List<Integer> inorderTraversal(TreeNode root) {
infixOrder(root);
return list;
}
private void infixOrder(TreeNode root) {
if (root == null)
return;
infixOrder(root.left);
list.add(root.val);
infixOrder(root.right);
}
}
非递归法:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<>();
if (root == null) return list;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}