程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode題解:Construct Binary Tree from Preorder and Inorder Traversal

LeetCode題解:Construct Binary Tree from Preorder and Inorder Traversal

編輯:C++入門知識

LeetCode題解: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.

題意:給定一棵樹的先序遍歷和中序遍歷,還原該樹

解決思路:在中序遍歷中,每一個根節點的左方為其左子樹,右方為右子樹;而在先序遍歷中第一個節點為根節點。利用這兩點可以解決

代碼:

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

    private TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder){
        if(preStart > preorder.length - 1 || inStart > inEnd){
            return null;
        }


        int index = 0;
        TreeNode root = new TreeNode(preorder[preStart]);
        for(int i = inStart; i <= inEnd; i++){
            if(inorder[i] == root.val){
                index = i;
                break;
            }
        }

        root.left = helper(preStart + 1, inStart, index - 1, preorder, inorder);
        root.right = helper(preStart + index - inStart + 1, index + 1, inEnd, preorder, inorder);

        return root;
    }
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved