• 用迭代法实现二叉树的前、中、后序遍历


    前序:
     public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> res=new ArrayList<Integer>();
         if (root==null) {
         return res;
        }
                         
                           Stack<TreeNode> stack=new Stack<>();
                         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;
           }
    中序:
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
       List<Integer> res=new ArrayList<Integer>();
                           Stack<TreeNode> stack=new Stack<>();
                           while (root!=null||stack.size()>0) {
          if (root!=null) {
           stack.add(root);
           root=root.left;
          }
          else {
           TreeNode temp=stack.pop();
           res.add(temp.val);
           root=temp.right;
          }
         }
                           return res;
        }
    }

    后序:把前序变一下,然后逆序
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
      List<Integer> res=new ArrayList<>();
                  if (root==null) {
        return res;
       }
                  Stack<TreeNode> stack=new Stack<>();
                  while (root!=null||!stack.isEmpty()) {
        if (root!=null) {
         res.add(root.val);
         stack.push(root);
         root=root.right;
        }
        else {
         TreeNode temp=stack.pop();
         root=temp.left;
        }
       }
                  Collections.reverse(res);
                  return res;
        }
    }
  • 相关阅读:
    webshell
    隐写术的总结
    A&DCTF
    JavaScript数组去重方法汇总
    Reverse Words in a String III
    DOM编程 --《高性能JavaScript》
    数据存储 --《高性能JavaScript》
    加载和执行 --《高性能JavaScript》
    算法和流程控制 --《高性能JavaScript》
    重载类型转换操作符(overload conversion operator)
  • 原文地址:https://www.cnblogs.com/wl889490/p/12623418.html
Copyright © 2020-2023  润新知