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


    前序:
     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;
        }
    }
  • 相关阅读:
    animation
    0201 ---背景 tableview
    0129 ---稳定定的 plist介绍
    0127 userdefault
    0127 数据库 我的专家
    0122 ---清理缓存
    0122 清楚缓存
    0122---screach
    0121 --view 可以当作线
    0119吧 iPhone 屏幕尺寸
  • 原文地址:https://www.cnblogs.com/wl889490/p/12623418.html
Copyright © 2020-2023  润新知