zoukankan      html  css  js  c++  java
  • 力扣144题、145题、94题(二叉树迭代遍历法)

      94、二叉树的中序遍历

    基本思想:

    中序遍历,左中右,先访问的是二叉树顶部的节点,

    然后一层一层向下访问,直到到达树左面的最底部,

    再开始处理节点(也就是在把节点的数值放进result数组中),

    这就造成了处理顺序和访问顺序是不一致的。

    在使用迭代法写中序遍历,就需要设置一个当前节点来帮助访问节点,栈则用来处理节点上的元素。

    代码:

    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new LinkedList<>();
            Stack<TreeNode> st = new Stack<>();
            TreeNode cur = root;
            while (!st.empty() || cur != null) {
                if (cur != null){
                    st.push(cur);
                    cur = cur.left;
                } else {
                    cur = st.pop();
                    result.add(cur.val);
                    cur = cur.right;
                }
            }
            return result;
        }

    144、二叉树的前序遍历

    具体实现:

    前序遍历是中左右,每次先处理的是中间节点

    先将根节点放入栈中,然后将右孩子加入栈,再加入左孩子

    这样出栈的时候才是中左右的顺序

    // 前序遍历顺序:中-左-右,入栈顺序:中-右-左
    class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root == null){
                return result;
            }
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()){
                TreeNode node = stack.pop();
                result.add(node.val);
                if (node.right != null){
                    stack.push(node.right);
                }
                if (node.left != null){
                    stack.push(node.left);
                }
            }
            return result;
        }
    }

    145、二叉树的后序遍历

    具体实现:

    前序遍历是中左右,后序遍历是左右中

    只需要调整前序遍历的代码顺序,变成中右左的遍历顺序,然后翻转result数组,就变成了左右中了

    // 后序遍历顺序 左-右-中 入栈顺序:中-左-右 出栈顺序:中-右-左, 最后翻转结果
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root == null){
                return result;
            }
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while (!stack.isEmpty()){
                TreeNode node = stack.pop();
                result.add(node.val);
                if (node.left != null){
                    stack.push(node.left);
                }
                if (node.right != null){
                    stack.push(node.right);
                }
            }
            Collections.reverse(result);
            return result;
        }
    }
  • 相关阅读:
    时间管理的心理建设与优先矩阵
    在oracle中计算时间差
    android环境搭建
    有效沟通的六个步骤
    5招教你把握Java性能监控(转自51testing)
    选项卡TabHost
    Excel导入导出数据库02
    画廊视图Gallery
    拖动条SeekBar及星级评分条
    在应用程序级别之外使用注册为allowDefinition='MachineToApplication' 的节是错误的
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15515196.html
Copyright © 2011-2022 走看看