I/P:
19
50 25 12 n n 37 30 n n n 75 62 n 70 n n 87 n n
O/P:
[50->25->12, 50->25->37->30, 50->75->62->70, 50->75->87]
https://leetcode.com/problems/binary-tree-paths/

Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
package pep.Day32;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class LeetCode_237_Binary_Tree_Paths {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int data, TreeNode left, TreeNode right) {
this.val = data;
this.left = left;
this.right = right;
}
}
public static class Pair {
TreeNode node;
int state;
Pair(TreeNode node, int state) {
this.node = node;
this.state = state;
}
}
public static TreeNode construct(Integer[] arr) {
TreeNode root = new TreeNode(arr[0], null, null);
Pair rtp = new Pair(root, 1);
Stack<Pair> st = new Stack<>();
st.push(rtp);
int idx = 0;
while (st.size() > 0) {
Pair top = st.peek();
if (top.state == 1) {
idx++;
if (arr[idx] != null) {
top.node.left = new TreeNode(arr[idx], null, null);
Pair lp = new Pair(top.node.left, 1);
st.push(lp);
} else {
top.node.left = null;
}
top.state++;
} else if (top.state == 2) {
idx++;
if (arr[idx] != null) {
top.node.right = new TreeNode(arr[idx], null, null);
Pair rp = new Pair(top.node.right, 1);
st.push(rp);
} else {
top.node.right = null;
}
top.state++;
} else {
st.pop();
}
}
return root;
}
public static void display(TreeNode node) {
if (node == null) {
return;
}
String str = "";
str += node.left == null ? "." : node.left.val + "";
str += " <- " + node.val + " -> ";
str += node.right == null ? "." : node.right.val + "";
System.out.println(str);
display(node.left);
display(node.right);
}
public static List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
helper(root, "", ans);
return ans;
}
public static void helper(TreeNode root, String ans, List<String> al) {
if (root == null)
return;
else if (root.left == null && root.right == null) {
ans += root.val;
al.add(ans);
return;
}
helper(root.left, ans + root.val + "->", al);
helper(root.right, ans + root.val + "->", al);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[n];
String[] values = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
if (values[i].equals("n") == false) {
arr[i] = Integer.parseInt(values[i]);
} else {
arr[i] = null;
}
}
int data = Integer.parseInt(br.readLine());
TreeNode root = construct(arr);
System.out.println(binaryTreePaths(root));
}
}
No comments:
Post a Comment