程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
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++入門知識

題目

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 ConstructBinaryTreeFromPreorderAndInorderTraversal {
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		return solve(preorder, 0, inorder, 0, inorder.length - 1);
	}

	private TreeNode solve(int[] preorder, int p, int[] inorder, int low,
			int high) {
		if (low > high) {
			return null;
		}
		TreeNode root = new TreeNode(preorder[p]);
		int cutPos = 0;
		for (int i = low; i <= high; ++i) {
			if (preorder[p] == inorder[i]) {
				cutPos = i;
				break;
			}
		}
		root.left = solve(preorder, p + 1, inorder, low, cutPos - 1);
		root.right = solve(preorder, p + cutPos - low + 1, inorder, cutPos + 1,
				high);
		return root;
	}
}

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