zoukankan      html  css  js  c++  java
  • 非递归方法遍历树(前序遍历、中序遍历及后续遍历)

    public List<Integer> preorderTraversal(TreeNode root) {
         List<Integer> res = new ArrayList<>();
         if (root == null) return res;
         LinkedList<TreeNode> stack = new LinkedList<>();
         stack.push(root);
         while (!stack.isEmpty()) {
             TreeNode node = stack.pop();
             res.add(node.val);
             if (node.right != null) stack.push(node.right);
             if (node.left != null) stack.push(node.left);
         }
         return res;
     }
    
     public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> res = new ArrayList<>();
         if (root == null) return res;
         LinkedList<TreeNode> stack = new LinkedList<>();
         TreeNode currNode = root;
    
         while (currNode != null) {
             stack.push(currNode);
             currNode = currNode.left;
         }
    
         while (!stack.isEmpty()) {
             currNode = stack.pop();
             res.add(currNode.val);
             currNode = currNode.right;
             while (currNode != null) {
                 stack.push(currNode);
                 currNode = currNode.left;
             }
         }
    
         return res;
     }
    
     public List<Integer> postorderTraversal(TreeNode root) {
         List<Integer> res = new LinkedList<>();
         if (root == null) return res;
         LinkedList<TreeNode> nodeStack = new LinkedList<>();
         Set<TreeNode> nodeSet = new HashSet<>();
    
         TreeNode currNode = root;
         while (currNode != null) {
             nodeStack.push(currNode);
             currNode = currNode.left;
         }
    
         while (!nodeStack.isEmpty()) {
             currNode = nodeStack.peek();
             if (currNode.right != null && !nodeSet.contains(currNode.right)) {
                 currNode = currNode.right;
                 while (currNode != null) {
                     nodeStack.push(currNode);
                     currNode = currNode.left;
                 }
             } else {
                 currNode = nodeStack.pop();
                 res.add(currNode.val);
                 nodeSet.add(currNode);
             }
         }
    
         return res;
     }
    
    
  • 相关阅读:
    python numpty 中shape的用法
    卷积神经网络中参数的计算
    linux学习
    数据结构排序算法总结
    剑指offer 刷题 01
    30-大道至简——随机森林如何将分类器由弱变强
    29-用python构造一棵决策树
    28-决策树算法——简单有效的概率模型
    27-如何度量分类算法的性能好坏(Scoring metrics for classification)
    26-史上最简单的分类算法——KNN
  • 原文地址:https://www.cnblogs.com/liulaolaiu/p/11744375.html
Copyright © 2011-2022 走看看