给定两个整数数组preOrder 和inOrder,其中preOrder是二叉树的先序遍历,inOrder是二叉树的中序遍历,请构造二叉树并返回其根节点
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */ public class Solution { Dictionary<int, int> inOrderMap = new Dictionary<int, int>(); public TreeNode BuildTree(int[] preOrder, int[] inOrder) { for (int i = 0; i < inOrder.Length; i++) inOrderMap.Add(inOrder[i], i); return BuildTreeByRecursion(preOrder, 0, preOrder.Length - 1, inOrder, 0, inOrder.Length - 1); } public TreeNode BuildTreeByRecursion(int[] preOrder, int preStart, int preEnd, int[] inOrder, int inStart, int inEnd) {
//先序遍历的第一个节点一定是当前子树的根节点 int rootValue = preOrder[preStart]; int rootInOrderIndex = inOrderMap[rootValue]; TreeNode root = new TreeNode(rootValue);
//当前子树左孩子节点数 int leftNodes = rootInOrderIndex - inStart;
//当前子树右孩子节点数
int rightNodes = inEnd - rootInOrderIndex; if (leftNodes > 0) root.left = BuildTreeByRecursion(preOrder, preStart + 1, preStart + leftNodes, inOrder, inStart, rootInOrderIndex - 1); if (rightNodes > 0) root.right = BuildTreeByRecursion(preOrder, preStart + leftNodes + 1, preEnd, inOrder, rootInOrderIndex + 1, inEnd); return root; } }
标签:preOrder,遍历,TreeNode,int,前序,二叉树,inOrder,public From: https://www.cnblogs.com/ayang1/p/17325619.html