【LeetCode】C# 105、Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:集团网络电话交换机 编辑:程序博客网 时间:2024/06/09 18:31

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

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

给定前序和中序排列的二叉树,重建这棵树。

思路:找到规律,
1. 先序遍历的从左数第一个为整棵树的根节点。
2. 中序遍历中根节点是左子树右子树的分割点。
然后通过先序遍历找到第一个点作为根节点,在中序遍历中找到根节点并记录index。
因为中序遍历中根节点左边为左子树,可以记录左右子树的长度并在先序遍历中依据这个长度找到左右子树的区间。
递归的建立好左子树和右子树就好。

/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {    public TreeNode BuildTree(int[] preorder, int[] inorder) {        return helper(0, 0, inorder.Length - 1, preorder, inorder);    }    public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {        if (preStart > preorder.Length - 1 || inStart > inEnd) {            return null;        }        TreeNode root = new TreeNode(preorder[preStart]);        int inIndex = 0; // Index of current root in inorder        for (int i = inStart; i <= inEnd; i++) {            if (inorder[i] == root.val) {                inIndex = i;            }        }        root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);        root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);        return root;    }}
阅读全文
0 0
原创粉丝点击