二叉树顾名思义,一个根节点只会有两个分叉对应,下图所示:

前序遍历先去拿它的左节点,拿完之后再去拿它左节点相邻的右节点,如数据结构是这样

第一中不考虑性能的方式的话,可以使用递归的方式去给他遍历
- function deepTree(data) {
- let arrayData = []
- let fun = (node) => {
- if (node) {
- arrayData.push(node.val)
- //遍历一下左子树
- fun(node.left)
- //遍历一下右子树
- fun(node.right)
- }
-
- fun(data)
- return arrayData
- }
- }
- deepTree(tree)
依次拿到值的 val;
第二种方式使用栈的形式遍历
- function preorderTraversal(root) {
- if (!root) return []
-
- let array = []
- let stack = [root]
-
- while (stack.length) {
- // 出栈
- let o = stack.pop()
- array.push(o.val)
-
- o.right && stack.push(o.right)
- o.left && stack.push(o.left)
- // console.log('oooo', o);
- }
- console.log(array);
- }
- preorderTraversal(tree)
考虑性能的算法使用 栈形式遍历;
时小记,终有成。