class Node {
constructor(data) {
this
.data = data;
this
.left =
null
;
this
.right =
null
;
}
}
function
buildTree(str) {
if
(str.length === 0 ||
str[0] ===
'N'
)
return
null
;
const ip = str.split(
' '
);
const root =
new
Node(parseInt(ip[0]));
const queue = [];
queue.push(root);
let i = 1;
while
(queue.length > 0 && i < ip.length)
{
const currNode = queue.shift();
let currVal = ip[i];
if
(currVal !==
'N'
) {
currNode.left =
new
Node(parseInt(currVal));
queue.push(currNode.left);
}
i++;
if
(i >= ip.length)
break
;
currVal = ip[i];
if
(currVal !==
'N'
) {
currNode.right =
new
Node(parseInt(currVal));
queue.push(currNode.right);
}
i++;
}
return
root;
}
class Solution {
traverseLeft(root, ans) {
if
(!root ||
(!root.left && !root.right))
return
;
ans.push(root.data);
if
(root.left)
this
.traverseLeft(root.left, ans);
else
this
.traverseLeft(root.right, ans);
}
traverseLeaf(root, ans) {
if
(!root)
return
;
if
(!root.left && !root.right) {
ans.push(root.data);
return
;
}
this
.traverseLeaf(root.left, ans);
this
.traverseLeaf(root.right, ans);
}
traverseRight(root, ans) {
if
(!root ||
(!root.left && !root.right))
return
;
if
(root.right)
this
.traverseRight(root.right, ans);
else
this
.traverseRight(root.left, ans);
ans.push(root.data);
}
boundary(root) {
const ans = [];
if
(!root)
return
ans;
ans.push(root.data);
this
.traverseLeft(root.left, ans);
this
.traverseLeaf(root.left, ans);
this
.traverseLeaf(root.right, ans);
this
.traverseRight(root.right, ans);
return
ans;
}
}
const solution =
new
Solution();
let input =
"20 8 22 4 12 N N N N 10 14"
;
let root = buildTree(input);
console.log(solution.boundary(root));