【问题标题】:Bottom up tree traversal [closed]自下而上的树遍历
【发布时间】:2017-09-07 17:17:58
【问题描述】:

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

按这样的顺序:1-3-8 | 4-6-3-8 | 7-6-3-8 | 13-14-10-8

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

let tree = {
  'parent': {
    'immediate child': {
      'post immediate child'
    }
    'second immediate child': {
      'second post immediate child'
    }
  }
}

function goUpTheTree(tree) {

}

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

【问题讨论】:

  • 如何(即在什么数据结构中)存储树?您应该提供更多信息,并自己付出一些努力。
  • 好的,一些更新:)

标签: javascript algorithm ecmascript-6 tree


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    您仍然可以自上而下遍历树。只需记住途中的节点,当您到达叶节点时,反向输出所有这些节点。

    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)。不过和你的定义基本一样。

    【讨论】:

      猜你喜欢
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 1970-01-01
      • 2017-05-13
      相关资源
      最近更新 更多