javascript - Find parent node in binary tree from value in javascript
问题描述
I have the following tree structure:
class Binarytree {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
insertLeft(val) {
this.left = val;
}
insertRight(val) {
this.right = val;
}
}
I'm trying to find a parent node from a node value. I created the function below:
const getParent = function(root, n, parent) {
if (!root) return null;
if (root.val === n) return parent;
else {
getParent(root.left, n, root);
getParent(root.right, n, root);
}
};
Here is my test case:
const tree = new BinaryTree(1);
const node2 = new BinaryTree(2);
const node3 = new BinaryTree(3);
const node4 = new BinaryTree(4);
const node5 = new BinaryTree(5);
node2.insertRight(node4);
node3.insertRight(node5);
tree.insertLeft(node2);
tree.insertRight(node3);
const test = getParent(tree, 4, tree);
It is always returning null.
解决方案
您需要返回嵌套调用getParent
. 您可以使用逻辑 OR||
链接调用
。
class BinaryTree {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
insertLeft(val) {
this.left = val;
}
insertRight(val) {
this.right = val;
}
}
const getParent = function(root, n, parent) {
if (!root) return null;
if (root.val === n) return parent;
// return and chain with logical OR
return getParent(root.left, n, root) || getParent(root.right, n, root);
}
const tree = new BinaryTree(1);
const node2 = new BinaryTree(2);
const node3 = new BinaryTree(3);
const node4 = new BinaryTree(4);
const node5 = new BinaryTree(5);
node2.insertRight(node4);
node3.insertRight(node5);
tree.insertLeft(node2);
tree.insertRight(node3);
const test = getParent(tree, 4, tree);
console.log(test);
推荐阅读
- ios - How to do transform CALayer without changing it's shape
- html - I'm getting stuck at vba runtime error 424
- python - 来自文本文件的 Python 代码 Mysql 连接字符串
- c# - 使用 SQL 查询合并三个表并获得一个输出
- wildcard - 如何处理狂野同情的结果
- android - How to send image in android
- azure - Implement row level security (RLS) in Azure Data Explorer
- android - how can i count the character limit of TextView?
- pandas - 使用 pandas 创建一个新列以获取不同货币的卢比换算值
- javascript - 播放 blob 视频文件