• 二叉树前、中、后、层次、遍历的非递归法


    一、二叉树

    非递归前序遍历

    class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<>();
            if(root == null) return res;
            Stack<TreeNode> st = new Stack<>();
            st.push(root);
            while(!st.empty()){
                TreeNode node = st.pop();
                res.add(node.val);
                if(node.right != null) st.push(node.right);
                if(node.left != null) st.push(node.left);
            }
            return res;
        }
    }

    非递归中序遍历

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

    非递归后序遍历

    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> res = new LinkedList<>();
            if(root == null) return res;
            Stack<TreeNode> st = new Stack<>();
            st.push(root);
            while(!st.isEmpty()){
                TreeNode node = st.pop();
                res.add(0,node.val);
                if (node.left != null) st.push(node.left);
                if (node.right != null) st.push(node.right);
            }
            return res;
        }
    }

    队列层次遍历

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> res = new ArrayList<>();
            Queue<TreeNode> queue = new LinkedList<>();
            if(root == null) return res;
            queue.add(root);
            while(!queue.isEmpty()){
                List<Integer> list = new LinkedList<>();
                int size = queue.size();
                while(size-- > 0){
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if(node.left!=null) queue.add(node.left);
                    if(node.right!=null) queue.add(node.right);
                }
                res.add(list);
            }
            return res;
        }
    }

    N叉树

  • 相关阅读:
    GUI编程
    Markdown学习
    [python3]正则表达式
    python3_json&pickle
    python3_module_sys
    python3_module_os
    Python3_module_random
    Pyhton3_module_time()
    Python3 正则表达式 Regular Expression
    Python循环对象
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10509883.html
Copyright © 2020-2023  润新知