自下而上的树遍历

时间:2017-09-07 17:17:58

标签: javascript algorithm ecmascript-6 tree

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

binary tree

按此顺序: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) {

}

非常感谢任何帮助...

2 个答案:

答案 0 :(得分:3)

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

template<typename F, std::size_t... Is, class Tup>
void dispatch_impl(F && f, std::index_sequence<Is...>, Tup && tup) {
    std::forward<F>(f)( std::get<Is>(std::move(tup))... );
}

template<typename F, typename... Args>
void dispatch(F && f, Args&&... args) {
    dispatch_impl(std::forward<F>(f),
             std::make_index_sequence<function_traits<F>::arity>{},
             std::forward_as_tuple(args...) );
}


template<class Vector, class F>
void over(Vector &&vec, F &&f)
{
    std::size_t i = 0;
    for (auto &&x : vec) {
        dispatch(std::forward<F>(f), x, i);
        ++i;
    }
}

答案 1 :(得分:1)

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

&#13;
&#13;
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, []);
&#13;
&#13;
&#13;

我使树结构更加结构化(即每个节点都有.value.left.right)。但它与你的定义基本相同。