image.png

递归

  1. class Solution {
  2. public List < Integer > inorderTraversal(TreeNode root) {
  3. List < Integer > res = new ArrayList < > ();
  4. helper(root, res);
  5. return res;
  6. }
  7. public void helper(TreeNode root, List < Integer > res) {
  8. if (root != null) {
  9. if (root.left != null) {
  10. helper(root.left, res);
  11. }
  12. res.add(root.val);
  13. if (root.right != null) {
  14. helper(root.right, res);
  15. }
  16. }
  17. }
  18. }

迭代

基于栈的遍历

  1. public List < Integer > inorderTraversal(TreeNode root) {
  2. List < Integer > res = new ArrayList < > ();
  3. Stack < TreeNode > stack = new Stack < > ();
  4. TreeNode curr = root;
  5. while (curr != null || !stack.isEmpty()) {
  6. while (curr != null) {
  7. stack.push(curr);
  8. curr = curr.left;
  9. }
  10. curr = stack.pop();
  11. res.add(curr.val);
  12. curr = curr.right;
  13. }
  14. return res;
  15. }