image.png
    解析:递归和非递归

    1. class Solution {
    2. List<Integer> res = new ArrayList<>();
    3. public List<Integer> inorderTraversal(TreeNode root) {
    4. /**
    5. * 递归
    6. */
    7. // if(root==null){
    8. // return new ArrayList<>();
    9. // }
    10. // inorderTraversal(root.left);
    11. // res.add(root.val);
    12. // inorderTraversal(root.right);
    13. // return res;
    14. /**
    15. * 非递归 压栈
    16. * 先全部压左,再压右
    17. */
    18. Stack<TreeNode> stack = new Stack<>();
    19. if (root == null) return new ArrayList<>();
    20. //压左孩子节点
    21. while (root != null || !stack.isEmpty()) {
    22. if (root != null) {
    23. stack.push(root);
    24. root = root.left;
    25. } else {
    26. TreeNode currRoot = stack.pop();
    27. res.add(currRoot.val);
    28. root = currRoot.right;
    29. }
    30. }
    31. return res;
    32. }
    33. }