Leetcode 从中序与后序遍历序列构造二叉树

打印 上一主题 下一主题

主题 984|帖子 984|积分 2952


java 递归实现
  1. class Solution {
  2.     private HashMap<Integer, Integer> inorderIndexMap;
  3.     private int postorderIndex;
  4.     public TreeNode buildTree(int[] inorder, int[] postorder) {
  5.         inorderIndexMap = new HashMap<>();
  6.         postorderIndex = postorder.length - 1;
  7.         for(int i = 0; i < inorder.length; i++) {
  8.             inorderIndexMap.put(inorder[i], i);
  9.         }
  10.         return Helper(postorder, 0, inorder.length - 1);
  11.     }
  12.     private TreeNode Helper(int[] postorder, int inorderStart, int inorderEnd) {
  13.         if(inorderStart > inorderEnd) return null;
  14.         //首先确定根节点的值
  15.         int rootValue = postorder[postorderIndex--];
  16.         TreeNode root = new TreeNode(rootValue);
  17.         //获取根节点在中序遍历中的索引,用于后面划分左右子树
  18.         int inorderIndex = inorderIndexMap.get(rootValue);
  19.         // 递归构建右子树和左子树
  20.         // 注意:需要先构建右子树,因为后序遍历的顺序是左右根
  21.         root.right = Helper(postorder, inorderIndex + 1, inorderEnd);
  22.         root.left = Helper(postorder, inorderStart, inorderIndex - 1);
  23.         return root;
  24.     }
  25. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

耶耶耶耶耶

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表