[leetcode][遞歸] [java]105題 根據前序和中序輸出二叉樹

數據結構學過,根據前序和中序可以確定唯一一棵二叉樹。

解法:理解是比較簡單的,前序確定根節點的值,中序找到根節點的位置,根節點的前半部分是左子樹,根的後半部分是右子樹,再構建左子樹,右子樹。以此構建二叉樹,當然理解起來很簡單,代碼需要使用遞歸訪問和實現。

例子:,構建樹:


代碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,inorder,0,0,inorder.length-1);
    }
    public TreeNode build(int[] pre, int[] in,int preStart,int inStart,int inEnd){
        if(preStart > pre.length - 1||inStart>inEnd) return null;
        TreeNode root = new TreeNode(pre[preStart]);
        int index = 0;//記錄根節點的位置
        for(int i=inStart;i<=inEnd;i++){
            if(root.val == in[i]){
                index = i;
                break;
            }
        }
        root.left = build(pre,in,preStart+1,inStart,index-1);//找出左子樹的各個位置
        root.right = build(pre,in,preStart+index-inStart+1,index+1,inEnd);//找出右子樹的各個位置
        return root;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章