[英]String representation of Binary Tree, find most distant from the tree root
This is an algorithm that I was given a while ago for a test and I couldn't figure it out. 这是我前一段时间进行测试的一种算法,我无法弄清楚。 Any ideas?
有任何想法吗?
You are given a recursive notation of a binary tree: each node of a tree is represented as a set of three elements: 您将获得二叉树的递归符号:树的每个节点都表示为三个元素的集合:
So, a tree can be written as (value left_subtree right_subtree)
. 因此,树可以写成
(value left_subtree right_subtree)
。
If a node doesn't exist then it is represented as an empty set: ()
. 如果节点不存在,则将其表示为空集合:(
()
。
Your task is to obtain a list of nodes, that are the most distant from the tree root, in the order from left to right. 您的任务是按从左到右的顺序获取离树根最远的节点列表。
In the notation of a node its value and subtrees are separated by exactly one space character. 在节点的表示法中,其值和子树仅由一个空格字符分隔。
Example: 例:
// 2
// / \
// / \
// / \
// / \
// / \
// 7 5
// / \ \
// / \ \
// 2 6 9
// / \ /
// / \ /
// 5 11 4
tree = "(2 (7 (2 () ()) (6 (5 () ()) (11 () ()))) (5 () (9 (4 () ()) ())))"
treeBottom(tree) // Desired output: [5, 11, 4].
Probably not most sophisticated solution, but it works.. 可能不是最复杂的解决方案,但它可以工作。
var tree = "(2 (7 (2 () ()) (6 (5 () ()) (11 () ()))) (5 () (9 (4 () ()) ())))"; var level = 0; var rootLeafs = [] var leaf = -1; var i; var parseToken = { "(": enterLevel, ")": leaveLevel, " ": separate, } function isValidTreeElement() { applyFn = parseToken[tree[i]]||parseNumber; return applyFn() } function enterLevel() { if (i > 0 && tree[i-1] != " ") { alert("Nodes must be separated by space"); return false; } level++; // entering new root leaf if (level == 2) { leaf++; rootLeafs[leaf] = []; } return true; } function leaveLevel() { level--; return true; } function separate() { if (i > 0 && tree[i-1] == " ") { alert("Multiple spaces in row"); return false; } return true; } function parseNumber() { var advance = tree.substring(i).indexOf(" "); if (advance < 1) { alert("Number must followed by space"); return false; } var num = Number(tree.substring(i,i+advance)); if (isNaN(num)) { alert("Expected number, given: " + tree.substring(i,i+advance)); return false; } i += advance - 1; // move index to last char of number // add value to current leaf level if (level > 1) { try { rootLeafs[leaf][level-2].push(num); } catch(e) { rootLeafs[leaf][level-2] = [num]; } } return true; } function walk() { for (i = 0; i < tree.length; i++) { if (!isValidTreeElement()) { return; } } // get last level from each root leaf var results = rootLeafs.reduce(function(a, b) { return a.concat(b.slice(-1)[0]); }, []); console.log('Result: ' + results); } walk();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.