码迷,mamicode.com
首页 > 其他好文 > 详细

先序和中序建立二叉树

时间:2015-04-23 13:16:06      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:


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 binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     static int getRootIndexInOrder(int inorder[], int root, int l, int r) {
        while (l <= r) {
            if (inorder[l] != root)
                l++;
            else break;
        }
        return l > r ? -1 : l;
    }

    static TreeNode create(int preorder[], int inorder[], int l1, int r1, int l2, int r2) {
        if (l1 > r1) return null;
        int root = preorder[l1];
        int index = getRootIndexInOrder(inorder, root, l2, r2);
        TreeNode rootNode = new TreeNode(root);

        TreeNode lchild = create(preorder, inorder, l1 + 1, l1 + index - l2, l2, index - 1);
        TreeNode rchild = create(preorder, inorder, l1 + index - l2 + 1, r1, index + 1, r2);

        rootNode.left = lchild;
        rootNode.right = rchild;
        return rootNode;
    }

     public TreeNode buildTree(int[] preorder, int[] inorder) {
        return create(preorder,inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }
}



先序和中序建立二叉树

标签:

原文地址:http://blog.csdn.net/wongson/article/details/45220231

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!