[go: up one dir, main page]

0% found this document useful (0 votes)
16 views2 pages

Views of Tree

Uploaded by

ndillisri4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Views of Tree

Uploaded by

ndillisri4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import java.util.

*;

class TreeNode {
char val;
TreeNode left;
TreeNode right;

public TreeNode(char val) {


this.val = val;
left = null;
right = null;
}
}

public class Main {


public static List<Character> leftview(TreeNode root) {
List<Character> leftView = new ArrayList<>();
if (root == null) {
return leftView;
}

Queue<TreeNode> queue = new LinkedList<>();


queue.offer(root);

while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
// Add the leftmost node at each level (i == 0)
if (i == 0) {
leftView.add(node.val);
}
// Enqueue left child first, then right child
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return leftView;
}

public static void main(String[] args) {


TreeNode root = new TreeNode('A');
root.left = new TreeNode('B');
root.right = new TreeNode('C');

root.left.left = new TreeNode('D');


root.left.right = new TreeNode('E');
root.right.left = new TreeNode('F');
root.right.right = new TreeNode('G');

List<Character> leftViewResult = leftview(root); // Fixed method name


System.out.print("Left View: ");
for (char node : leftViewResult) {
System.out.print(node + " ");
}
System.out.println(); // Fixed the invalid print statement
}
}

You might also like