Sponsored
Sponsored
This approach uses a level-order traversal technique with the help of a queue to check if the binary tree is complete. In a complete binary tree, once a null node is encountered while doing a level order traversal, all subsequent nodes must also be null to satisfy completeness.
Time Complexity: O(n), where n is the number of nodes in the tree. We traverse each node once.
Space Complexity: O(n), where n is the number of nodes, used for the queue storage.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12 public bool IsCompleteTree(TreeNode root) {
13 if (root == null) return true;
14 Queue<TreeNode> queue = new Queue<TreeNode>();
15 queue.Enqueue(root);
16 bool encounteredNull = false;
17 while (queue.Count > 0) {
18 TreeNode current = queue.Dequeue();
19 if (current == null) {
20 encounteredNull = true;
21 } else {
22 if (encounteredNull) return false;
23 queue.Enqueue(current.left);
24 queue.Enqueue(current.right);
25 }
26 }
27 return true;
28 }
29}
C# uses the System.Collections.Generic.Queue for node traversal. The solution logic remains consistent, ensuring detection of any improper null arrangements.
This approach utilizes depth-first search to gather information regarding the number of nodes and their indices. Using these, we check the compactness of the tree at each level to ensure all nodes fit the complete binary tree property.
Time Complexity: O(n).
Space Complexity: O(n), due to recursive stack usage.
1
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
private int CountNodes(TreeNode root) {
if (root == null) return 0;
return 1 + CountNodes(root.left) + CountNodes(root.right);
}
private bool DFS(TreeNode node, int index, int nodeCount) {
if (node == null) return true;
if (index >= nodeCount) return false;
return DFS(node.left, 2 * index + 1, nodeCount) && DFS(node.right, 2 * index + 2, nodeCount);
}
public bool IsCompleteTree(TreeNode root) {
int nodeCount = CountNodes(root);
return DFS(root, 0, nodeCount);
}
}
C# employs recursive calls to count nodes and check each node's index, ensuring a consecutive sequence aligning with that of a complete binary tree.