题目描述:给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
编码实现:
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (null == preorder || preorder.length == 0){
return null;
}
Stack s = new Stack<>();
TreeNode root = new TreeNode(preorder[0]);
TreeNode cur = root;
for (int i = 1, j = 0; i < preorder.length; i++) {
if (cur.val != inorder[j]) {
cur.left = new TreeNode(preorder[i]);
s.push(cur);
cur = cur.left;
} else {
j++;
while (!s.empty() && s.peek().val == inorder[j]) {
cur = s.pop();
j++;
}
cur = cur.right = new TreeNode(preorder[i]);
}
}
return root;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)