construct-binary-tree-from-inorder-and-postorder-traversal Java code

来源:互联网 发布:内蒙古网络春晚 编辑:程序博客网 时间:2024/06/15 03:07

Given inorder and postorder 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 {    public TreeNode buildTree(int[] inorder, int[] postorder) {        int len = postorder.length;        if(len == 0)return null;        int root_val = postorder[len - 1];        TreeNode root = new TreeNode(root_val);        int root_index;        for(root_index = 0; root_index < len; root_index++){            if(inorder[root_index] == root_val)break;        }        int left_len =root_index;        int right_len = len - root_index - 1;        int[] left_in = new int[left_len];        int[] left_post = new int[left_len];        int[] right_in = new int[right_len];        int[] right_post = new int[right_len];        for(int i = 0; i < root_index; i++){            left_in[i] = inorder[i];            left_post[i] = postorder[i];        }        for(int i = root_index + 1; i < len; i++){            right_in[i - root_index - 1] = inorder[i];        }        for(int i = root_index; i < len - 1; i++){            right_post[i - root_index] = postorder[i];        }        TreeNode left = buildTree(left_in, left_post);        TreeNode right = buildTree(right_in, right_post);        root.left = left;        root.right = right;        return root;    }}
阅读全文
0 0
原创粉丝点击