emm
面试:疯狂被怼。。。
1.一颗二叉搜索树,怎么找到第k大的元素,不允许使用额外空间;
考察二叉搜索树(二叉排序树)特点:
二叉搜索树性质:
- 若它的左子树不为空,则左子树上所有结点的值均小于它的根结点的值,若它的右子树不为空,则右子树上所有结点的值均大于它的根结点的值;
- 二叉搜索树中序遍历有序
剑指Offer原题:二叉搜索树的第k个节点
写法1:
public class Solution {
private int cnt = 0;
private TreeNode res;
TreeNode KthNode(TreeNode pRoot, int k) {
if(pRoot == null)
return null;
KthNode(pRoot.left , k);
cnt++;
if(cnt == k)
res = pRoot;
KthNode(pRoot.right , k);
return res;
}
}
写法2:
public class Solution {
private int cnt = 0;
private TreeNode res;
TreeNode KthNode(TreeNode pRoot, int k) {
inorder(pRoot , k);
return res;
}
private void inorder(TreeNode root , int k)
{
if(root == null)
return;
inorder(root.left , k); //左
cnt++;
if(cnt == k)
res = root;
inorder(root.right , k); //右
}
}
2.循环队列
循环队列实现:数组空出一个元素位不使用,来帮助判断数组是否满;(使用原子操作函数cas实现线程安全)
循环队列线程安全实现:https://blog.youkuaiyun.com/u014618114/article/details/108125101
class Main{
int[] data;
int head;
int tail;
public Main()
{
data = new int[10000];
head = 0;
tail = 0;
}
public boolean push(int d)
{
if((tail + 1) % 10000 == head) //判断队列是否满
return false;
data[tail] = d;
tail = (tail + 1) % 10000;
return true;
}
public int pop()
{
if(tail == head) //判断队列是否为空
return -1;
int tmp = data[head];
head = (head + 1) % 10000;
}
}

3. 两棵二叉树,各自结点任意次数交换,判断是否同构
找不到原题了,看一个类似的:https://pintia.cn/problem-sets/15/problems/711
参考:https://blog.youkuaiyun.com/lafengxiaoyu/article/details/53256499
public class Main{
public boolean isSame(TreeNode root1, TreeNode root2)
{
if(root1 == null && root2 == null)
return true;
else if((root1 == null && root2 != null) || (root1 != null && root2 == null))
return false;
else if(root1.val != root2.val)
return false;
else if(root1.left == null && root2.left == null)
return isSame(root1.right , root2.right);
if(((root1.left != null) && (root2.left != null)) && (root1.left.val == root2.left.val))
return (isSame(root1.left , root2.left) && isSame(root1.right , root2.right));
else
return (isSame(root1.left , root2.right) && isSame(root1.right , root2.left));
}
}
class TreeNode{
int val;
TreeNode left;
TreeNode right;
}
4. 二叉树镜像
操作给定的二叉树,将其变换为源二叉树的镜像。
https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&from=cyc_github&tab=answerKey
public class Solution {
public void Mirror(TreeNode root) {
if(root == null)
return;
//swap
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
//递归
Mirror(root.left);
Mirror(root.right);
}
}

2万+



被折叠的 条评论
为什么被折叠?



