标签:nbsp tco size within roots val pre sub 后序
public TreeNode find(int[] preorder, int[] inorder,int j, int start, int end) { if (j > preorder.length - 1 || start > end) { return null; } TreeNode root = new TreeNode(preorder[j]); int flag = 0; for (int i = start; i <= end; i++) { if (inorder[i] == root.val) { flag = i; } } root.left = find(preorder, inorder,j + 1,start, flag - 1); root.right = find(preorder, inorder,j + flag - start + 1, flag + 1, end); return root; }
so basically flag-start is size of the roots left subtree,
therefore to get the start of right subtree you gotta get to the start of the first value of right subtree within preorder.
relative start of the root + left + right tree (j) + left sub tree size (flag - start) + 1 (the root).
【flag-start】左子树的大小
【j】前序从j基础上开始遍历的
【+1】根节点
【前序遍历位置】=【基础位置J】+【左子树大小FLAG-START】+【下一节点1】
标签:nbsp tco size within roots val pre sub 后序
原文地址:https://www.cnblogs.com/inku/p/9953470.html