一、二叉树搜索树的最小绝对差
二叉搜索树可以看做是有序数组的问题,中序遍历
递归法 中序遍历
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var getMinimumDifference = function (root) {
let pre = null
let result = Infinity
function dfs(root) {
if (!root) {
return
}
dfs(root.left)
if (pre !== null) {
result = Math.min(result, Math.abs(Number(pre.val) - Number(root.val)))
}
pre = root
dfs(root.right)
}
dfs(root)
return result
};
迭代法
var getMinimumDifference = function (root) {
let result = Infinity
let pre = null
let stack = []
let cur = root
while(stack.length || cur) {
if(cur) {
stack.push(cur)
cur = cur.left
} else {
let node = stack.pop()
if(pre !== null) {
result = Math.min(result, Math.abs(Number(node.val - pre.val)))
}
pre = node
cur = node.right
}
}
return result
};
二、二叉搜索树中的众数
递归法
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var findMode = function(root) {
let result = []
let pre = null
let count = 0
let maxCount = 0
function dfs(root) {
if(!root) {
return
}
dfs(root.left)
if(pre === null) {
count = 1
} else if(pre.val === root.val) {
count++
} else {
count = 1
}
pre = root
if(count === maxCount) {
result.push(root.val)
}
if(count > maxCount) {
maxCount = count
result = [root.val]
}
dfs(root.right)
}
dfs(root)
return result
};
迭代法
var findMode = function(root) {
let result = []
let pre = null
let count = 0
let maxCount = 0
let stack = []
let cur = root
while(stack.length || cur) {
if(cur) {
stack.push(cur)
cur = cur.left
} else {
let node = stack.pop()
if(!pre) {
count = 1
} else if(pre.val === node.val) {
count++
} else {
count = 1
}
pre = node
if(count === maxCount) {
result.push(node.val)
}
if(count > maxCount) {
maxCount = count
result = []
result.push(node.val)
}
cur = node.right
}
}
return result
};
三、二叉树的最近公共祖先
递归法,后序遍历
拿到左子树和右子树的结果后,判断如果都有值,则root就是最近公共祖先,一直把该值返回到顶层即可
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
var lowestCommonAncestor = function(root, p, q) {
if(!root || root === q || root === p) {
return root
}
let left = lowestCommonAncestor(root.left, p, q)
let right = lowestCommonAncestor(root.right, p, q)
if(left && right) {
return root
} else if(!left && right) {
return right
} else if(left && !right) {
return left
} else {
return null
}
};