Construct Binary Tree from Preorder and Inorder Traversal - Leetcode

来源:互联网 发布:淘宝扣分清零时间 编辑:程序博客网 时间:2024/05/19 18:13
/** * 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[] preorder, int[] inorder) {        return buildTreeHelper(preorder, 0 ,preorder.length-1, inorder, 0, inorder.length-1);    }        private TreeNode buildTreeHelper(int[] pre, int pre_start, int pre_end, int[] in, int in_start, int in_end){        if(in_start > in_end || pre_start > pre_end)           return null;        int root_val= pre[pre_start];        int root_id=0;        for(int i=in_start; i<=in_end; i++){            if(in[i] == root_val){               root_id = i;               break;            }        }                int distance = root_id-in_start;        TreeNode root = new TreeNode(root_val);                root.left = buildTreeHelper(pre, pre_start+1, pre_start+distance, in, in_start, root_id-1);        root.right = buildTreeHelper(pre, pre_start+distance+1, pre_end, in, root_id+1, in_end);                return root;    }    }
1)找到根节点,2)求出左子树的个数,逐个深入扩展左根节点,右根节点。
*题目中的特征是:
先序遍历:<span style="background-color: rgb(255, 102, 102);">中</span>左右
中序遍历:左<span style="background-color: rgb(255, 102, 102);">中</span>右
后序遍历:左右<span style="background-color: rgb(255, 102, 102);">中</span>
0 0
原创粉丝点击