Skip to content

Instantly share code, notes, and snippets.

@smallyunet
Last active November 4, 2019 03:31
Show Gist options
  • Save smallyunet/feaf94c931339766f49119e1f12030f9 to your computer and use it in GitHub Desktop.
Save smallyunet/feaf94c931339766f49119e1f12030f9 to your computer and use it in GitHub Desktop.
Build a sequence binary tree through an array
/**
* @description Sequence binary tree structure
* @author smallyu
* @date 2019/11/4 10:20
*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
/**
* @description Build a sequence binary tree through an array
* @param nums
*/
TreeNode(int[] nums) {
this.val = nums[0];
LinkedList<TreeNode> list = new LinkedList<>();
list.offer(this);
for (int i = 1; i < nums.length - 1; i += 2) {
TreeNode node = list.poll();
node.left = new TreeNode(nums[i]);
node.right = new TreeNode(nums[i+1]);
list.offer(node.left);
list.offer(node.right);
}
}
@Override
public String toString() {
LinkedList<TreeNode> list = new LinkedList<>();
list.offer(this);
ArrayList<Integer> res = new ArrayList<>();
while (!list.isEmpty()) {
TreeNode node = list.poll();
res.add(node.val);
if (node.left != null) {
list.offer(node.left);
}
if (node.right != null) {
list.offer(node.right);
}
}
return res.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment