二叉树part07
注意这里说的是任意两个节点,而不一定要是父子节点之间
所有拿到BST的中序遍历结果,由于在BST中中序是升序的,在升序中就能找到最小值
/**
* 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 res = [];
inOrder(root, res);
console.log(res);
let min = Infinity;
for(let i = 1; i < res.length; i++){
min = Math.min(min, Math.abs(res[i] - res[i - 1]));
}
return min;
};
function inOrder(root, res){
if(!root) return;
inOrder(root.left, res);
res.push(root.val);
inOrder(root.right, res);
}
感觉有更优的写法
/**
* 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 arr = [];
inOrder(root, arr);
let res = [];
let j = 0;
let maxLen = -1;
console.log(arr);
for(let i = 0; i < arr.length; i++){
if(arr[i] != arr[j]){
if( i - j > maxLen){
maxLen = i - j;
res = [arr[j]];
}else if(i - j == maxLen){
res.push(arr[j]);
}
j = i;
}
if(i == arr.length - 1){
if(i - j + 1 > maxLen){
res = [arr[i]];
}else if(i - j + 1 == maxLen) res.push(arr[i])
}
}
return res;
};
function inOrder(root, res){
if(!root) return;
inOrder(root.left, res);
res.push(root.val);
inOrder(root.right, res);
}
有点难向,想到了用后序遍历,但是自己想的时候理不清回溯的逻辑
/**
* 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 === null || root === p || root === q) 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 null;
};