105. Construct Binary Tree from Preorder and Inorder Traversal

网友投稿 240 2022-09-17

105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { HashMap map = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } TreeNode root = null; TreeNode p = root; Stack stack = new Stack<>(); for (int i = 0; i < preorder.length; i++) { int temp = map.get(preorder[i]); TreeNode node = new TreeNode(preorder[i]); if (stack.isEmpty()) { root = node; p = root; } else { if (temp < map.get(stack.peek().val)) { p.left = node; p = p.left; } else { while (!stack.isEmpty() && temp > map.get(stack.peek().val)) { p = stack.pop(); } p.right = node; p = p.right; } } stack.add(node); } return root; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:“微信豆”功能上线:1块钱10个豆,加码布局视频号直播!
下一篇:319. Bulb Switcher
相关文章

 发表评论

暂时没有评论,来抢沙发吧~