您的位置:首页 > 其它

由前序遍历数组和中序遍历数组重建二叉树

2018-03-06 15:50 288 查看
在Leetcode中有一道题目105. Construct Binary Tree from Preorder and Inorder Traversal是要求由前序遍历数组和中序遍历数组重建二叉树的,以下是一段比较高效的代码以及注释。/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
class Solution {
private int pre = 0;
private int in = 0;

public TreeNode buildTree(int[] preorder, int[] inorder) {
return helper(preorder, inorder, null);
}
//rootVal构造左子树时到达父结点; 构造右子树时到达父结点的父结点
public TreeNode helper(int[] preorder, int[] inorder, Integer rootVal){
if(pre >= preorder.length || in >= inorder.length || (rootVal != null && rootVal == inorder[in]))
return null;

TreeNode node = new TreeNode(preorder[pre++]);
node.left = helper(preorder, inorder, node.val); //构造左子树,以当前结点为界
in++; //与pre++操作相对应

node.right = helper(preorder, inorder, rootVal); //构造右子树, 以当前结点的父结点为界

return node;
}
}
//98%//例子: 每个在前序数组中依次出现的结点, 在中序数组中, 该结点左边的为左子树, 右边直到其父结点的为右子树
//前序遍历: 1 2 4 7 3 5 6 8
//中序遍历: 4 7 2 1 5 3 8 6
//对于结点1,其左子树由4 7 2构成, 右子树由5 3 8 6构成
//对于结点2,其左子树由4 7构成, 右子树为空(2和1之间没有结点)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐