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


    前序:
     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;
        }
    }
  • 相关阅读:
    C++ 虚函数在基类与派生类对象间的表现及其分析
    借@阿里巴巴 耍了个帅——HTML5 JavaScript实现图片文字识别与提取
    Dede(织梦) CMS SQL Injection Vulnerability
    dedecms v5.5 final getwebshell exploit(datalistcp.class.php)
    DEDECMS网站管理系统Get Shell漏洞
    织梦(Dedecms)select_soft_post.php页面变量未初始漏洞
    织梦(Dedecms) 5.1 feedback_js.php 注入漏洞
    织梦(DEDE)CMS V5.3 覆盖任意变量导致远程包含漏洞
    dedecms织梦 v5.5 两处跨站漏洞
    dedecms织梦 v5.6 两处跨站漏洞
  • 原文地址:https://www.cnblogs.com/wl889490/p/12623418.html
Copyright © 2020-2023  润新知