• 94. 二叉树的中序遍历(递归+迭代)


    题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

    解题思路: 

    方法一:递归

    中序遍历的操作定义为,若二叉树为空,则空操作,否则:

    1. 中序遍历左子树
    2. 访问根节点
    3. 中序遍历右子树

    AC代码

    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List inorderTraversal(TreeNode root) {
    18. List result = new ArrayList<>();
    19. process(result,root);
    20. return result;
    21. }
    22. public void process(List result ,TreeNode root){
    23. if (root==null){
    24. return;
    25. }
    26. //中序遍历左子树
    27. process(result,root.left);
    28. //访问根节点
    29. result.add(root.val);
    30. //中序遍历右子树
    31. process(result,root.right);
    32. }
    33. }

     方法二:迭代,递归的循环版本,借助栈来完成递归,

    如果root !=null 或者 stack的大小不为0,则循环执行:

    1. 如果root !=null,循环将节点和其左孩子入栈执行:
      1. stack.push(root):将root入栈
      2. root=root.left:继续将root的左孩子入栈
    2. 上面循环结束后,栈顶节点没有左孩子,此时可以访问该节点:
      1. root = stack.pop():
      2. result.add(root.val):该节点没有左孩子,可以访问该节点
    3. 令root = root.right:对该节点的右孩子继续执行上述操作,如果其右孩子有左孩子,将左孩子入栈 
    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. public List inorderTraversal(TreeNode root) {
    18. List result = new ArrayList<>();
    19. Deque stack = new LinkedList<>();
    20. while (root!=null||!stack.isEmpty()){
    21. //遍历左子树
    22. while (root!=null){
    23. stack.push(root);
    24. root=root.left;
    25. }
    26. root = stack.pop();
    27. //访问根节点
    28. result.add(root.val);
    29. //遍历右子树
    30. root=root.right;
    31. }
    32. return result;
    33. }
    34. }

     

  • 相关阅读:
    基数排序详解(LSD方法+MSD方法+思路+图解+代码)
    Maven是什么? Maven的概念+作用
    IntelliJ IDEA 2023.2 主要更新了什么?(图文版)
    舵机调试上位机
    Python读取mongodb数据库
    【计算机网络】UDP协议
    Nginx学习总结
    Vue通知提醒框(Notification)
    YOLOv5 最详细的源码逐行解读(二: 网络结构)
    【Go语言精进之路】构建高效Go程序:零值可用、使用复合字面值作为初值构造器
  • 原文地址:https://blog.csdn.net/qq_40707370/article/details/133848337