首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自下而上的树遍历

自下而上的树遍历
EN

Stack Overflow用户
提问于 2017-09-07 17:17:58
回答 2查看 2.5K关注 0票数 1

如果您能向我解释如何遍历这棵树(最好使用javascript),我将非常感激:

按以下顺序排列: 1-3-8连4-6-3-8连7-6-3-8

模拟的数据可以如下所示:

代码语言:javascript
复制
let tree = {
  'parent': {
    'immediate child': {
      'post immediate child'
    }
    'second immediate child': {
      'second post immediate child'
    }
  }
}

function goUpTheTree(tree) {

}

任何帮助都将不胜感激..。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-07 18:01:12

基本上,您可以存储节点的路径,如果发现节点没有任何左或右分支,则以路径作为值。

代码语言:javascript
复制
function getBottomUp(node, path) {
    path = [node.value].concat(path || []);
    if (!node.left && !node.right) {
        console.log(JSON.stringify(path));
        return;
    }
    node.left && getBottomUp(node.left, path);
    node.right && getBottomUp(node.right, path);
}

var tree = { value: 8, left: { value: 3, left: { value: 1 }, right: { value: 6, left: { value: 4 }, right: { value: 7 } } }, right: { value: 10, right: { value: 14, left: { value: 3 } } } };

getBottomUp(tree);

票数 3
EN

Stack Overflow用户

发布于 2017-09-07 18:00:51

你仍然可以从上到下穿过这棵树.只需记住在您的途中的节点,当您到达一个叶节点,输出所有这些节点反向。

代码语言:javascript
复制
var tree = 	{
	"value": 8,
	"left": {
		"value": 3,
		"left": {
			"value": 1,
			"left": null,
			"right": null
		},
		"right": {
			"value": 6,
			"left": {
				"value": 4,
				"left": null,
				"right": null
			},
			"right": {
				"value": 7,
				"left": null,
				"right": null
			}
		}
	},
	"right": {
		"value": 10,
		"left": null,
		"right": {
			"value": 14,
			"left": {
				"value": 13,
				"left": null,
				"right": null
			},
			"right": null
		}
	}
}

function goUpTheTree(node, pathFromRoot) {
    //add the current node to the path
	pathFromRoot.push(node.value);
	if(node.left == null && node.right == null) {
		//this is a leaf node
		//print the path in reverse
		pathString = "";
		pathFromRoot.forEach(function(element) { pathString = element + " " + pathString; });
		console.log(pathString);
	}
	if(node.left != null)
		goUpTheTree(node.left, pathFromRoot);
	if(node.right != null)
		goUpTheTree(node.right, pathFromRoot);
    //remove the current node from the path
	pathFromRoot.pop();
}

goUpTheTree(tree, []);

我使树结构更加结构化(即每个节点都有.value.left.right)。但基本上和你的定义是一样的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46101964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档