最近要開始找工作啦,很久很久之前用python和java刷過刷數據結構和算法,現在已經記憶模糊了。而且從來沒有用js實現過,這次就用js刷一遍好了。
二叉樹
首先定義樹的節點,包含數據域和后驅指針
function TreeNode(val){
this.val = val
this.left = this.right = null
}
然后定義樹,樹在初始化時應當定義其根節點
function BinaryTree(root){
this.root = root
}
樹的遍歷
樹的遍歷常見的有四種,包括先序遍歷,中序遍歷,后序遍歷。
先序遍歷的意思就是先處理當前節點,再處理當前節點的左右子樹
BinaryTree.prototype.preorder = function(){
ans = []
function helper(node){
if(node){
ans.push(node.val)
helper(node.left)
helper(node.right)
}
}
helper(this.root)
return ans
}
同理,我們也可以很容易的寫出,中序遍歷和后序遍歷
BinaryTree.prototype.inorder = function(){
ans = []
function helper(node){
if(node){
helper(node.left)
ans.push(node.val)
helper(node.right)
}
}
helper(this.root)
return ans
}
BinaryTree.prototype.postorder = function(){
ans = []
function helper(node){
if(node){
helper(node.left)
helper(node.right)
ans.push(node.val)
}
}
helper(this.root)
return ans
}
層序遍歷稍微復雜一點,需要用一個隊列來輔助,思路就是先把根節點遍歷,然后把根節點的子節點放入待遍歷層這(隊列),然后不斷處理和更新這個隊列直到其為空
BinaryTree.prototype.levelorder = function(){
var level = [this.root]
var ans = []
var tmp
while(level.length > 0){
ans = ans.concat(level.map((node) => node.val))
tmp = []
level.forEach((node) => {
if(node.left) tmp.push(node.left)
if(node.right) tmp.push(node.right)
})
level = tmp
}
return ans
}
樹的高度
遞歸調用就好啦
BinaryTree.prototype.getHeight = function(node){
if(typeof node === 'undefined') node = this.root
if (!node) return 0
return Math.max(this.getHeight(node.left), this.getHeight(node.right)) + 1
}
樹的 最大/最小 深度
BinaryTree.prototype.maxDepth = function(node){
if (typeof node === 'undefined') node = this.root
if(node){
return Math.max(this.maxDepth(node.left), this.maxDepth(node.right)) + 1
}
return 0
}
BinaryTree.prototype.minDepth = function(node){
if (typeof node === 'undefined') node = this.root
if (!node) return 0
if (!node.left || !node.right){
return this.minDepth(node.left) + this.minDepth(node.right) + 1
}
return Math.min(this.minDepth(node.left), this.minDepth(node.right)) + 1
}
判斷兩棵樹是否相同
function isSameTree(p,q){
if(!p || !q) return p === q
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
}
判斷一棵樹是否平衡
//Balanced ?
BinaryTree.prototype.isBalanced = function(node){
if(typeof node === 'undefined') node = this.root
if(!node) return true
return Math.abs(this.getHeight(node.left) - this.getHeight(node.right)) < 2 && this.isBalanced(node.left) && this.isBalanced(node.right)
}