先/前序遍歷、中序遍歷、後序遍歷、層序遍歷
根左右-先訪問根節點,然後左子樹,最後右子樹
結果是:6, 3, 2, 10, 8, 12, 14
/**
* binarynode
* @param tree
* @param arr
* @return
*/function
preorder
(tree, arr =
)return arr;
}
/**
* binarynode
* @param tree
* @return
*/function
preorder
(tree)
current = tem.
pop(
).right;
}return res;
}
左根右-先訪問左子樹,然後根節點,最後右子樹
結果是:2, 3, 6, 8, 10, 12, 14
/**
* binarynode
* @param tree
* @param arr
* @return
*/function
middle
(tree, arr =
)return arr;
}
/**
* binarynode
* @param tree
* @return
*/function
middle
(tree)
current = tem.
pop();
res.
push
(current.key)
; current = current.right;
}return res;
}
左右根-先訪問左子樹,然後右子樹,最後根節點
結果是:2, 3, 8, 14, 12, 10, 6
/**
* binarynode
* @param tree
* @param arr
* @return
*/function
after
(tree, arr =
)return arr;
}
/**
* binarynode
* @param tree
* @return
*/function
after
(tree)
current = tem[tem.length -1]
;if(current.right &&
(current.right != last)
)else
}return res;
}
先根節點,然後從上往下每一層從左往右逐層
結果是:6, 3, 10, 2, 8, 12, 14
/**
* binarynode
* @param tree
* @param arr
* @param floor
* @return
*/function
level
(tree, arr =
, floor =0)
arr[floor]
.push
(tree.key)
;level
(tree.left, arr, floor +1)
;level
(tree.right, arr, floor +1)
;}return arr;
}/**
* @param tree
* @return
*/function
leveleach
(tree));
// res = levelarr.flat();
return res;
}
/**
* binarynode
* @param tree
* @return
*/function
level
(tree)
if(item.right)})
; floor++
; current = tem;
}return res;
}/**
* @param tree
* @return
*/function
leveleach
(tree));
// res = levelarr.flat();
return res;
}
結語:
每種遍歷提供兩種方法,遞迴和非遞迴。層序遍歷中第二個方法只為打平結果陣列。
演算法之二叉樹各種遍歷
樹形結構是一類重要的非線性資料結構,其中以樹和二叉樹最為常用。二叉樹是每個結點最多有兩個子樹的有序樹。通常子樹的根被稱作 左子樹 left subtree 和 右子樹 right subtree 二叉樹常被用作二叉查詢樹和二叉堆或是二叉排序樹。二叉樹的每個結點至多只有二棵子樹 不存在度大於2的結點 ...
演算法之二叉樹各種遍歷
樹形結構是一類重要的非線性資料結構,其中以樹和二叉樹最為常用。二叉樹是每個結點最多有兩個子樹的有序樹。通常子樹的根被稱作 左子樹 left subtree 和 右子樹 right subtree 二叉樹常被用作二叉查詢樹和二叉堆或是二叉排序樹。二叉樹的每個結點至多只有二棵子樹 不存在度大於2的結點 ...
演算法之二叉樹各種遍歷
樹形結構是一類重要的非線性資料結構,其中以樹和二叉樹最為常用。二叉樹是每個結點最多有兩個子樹的有序樹。通常子樹的根被稱作 左子樹 left subtree 和 右子樹 right subtree 二叉樹常被用作二叉查詢樹和二叉堆或是二叉排序樹。二叉樹的每個結點至多只有二棵子樹 不存在度大於2的結點 ...