二叉树实战 22 题,速度收藏吧!

先上二叉树的数据结构:

classTreeNode{

intval;

//左孩子

TreeNode left;

//右孩子

TreeNode right;

}

二叉树的题目普遍可以用递归和迭代的方式来解

1. 求二叉树的最大深度

intmaxDeath(TreeNode node){

if(node==null){

return0;

}

intleft = maxDeath(node.left);

intright = maxDeath(node.right);

returnMath.max(left,right) +1;

}

2. 求二叉树的最小深度

intgetMinDepth(TreeNode root){

if(root ==null){

return0;

}

returngetMin(root);

}

intgetMin(TreeNode root){

if(root ==null){

returnInteger.MAX_VALUE;

}

if(root.left ==null&&root.right ==null){

return1;

}

returnMath.min(getMin(root.left),getMin(root.right)) +1;

}

3. 求二叉树中节点的个数

intnumOfTreeNode(TreeNode root){

if(root ==null){

return0;

}

intleft = numOfTreeNode(root.left);

intright = numOfTreeNode(root.right);

returnleft + right +1;

}

4. 求二叉树中叶子节点的个数

intnumsOfNoChildNode(TreeNode root){

if(root ==null){

return0;

}

if(root.left==null&&root.right==null){

return1;

}

returnnumsOfNodeTreeNode(root.left)+numsOfNodeTreeNode(root.right);

}

5. 求二叉树中第k层节点的个数

intnumsOfkLevelTreeNode(TreeNode root,intk){

if(root ==null||k<1){

return0;

}

if(k==1){

return1;

}

intnumsLeft = numsOfkLevelTreeNode(root.left,k-1);

intnumsRight = numsOfkLevelTreeNode(root.right,k-1);

returnnumsLeft + numsRight;

}

6. 判断二叉树是否是平衡二叉树

booleanisBalanced(TreeNode node){

returnmaxDeath2(node)!=-1;

}

intmaxDeath2(TreeNode node){

if(node ==null){

return0;

}

intleft = maxDeath2(node.left);

intright = maxDeath2(node.right);

if(left==-1||right==-1||Math.abs(left-right)>1){

return-1;

}

returnMath.max(left, right) +1;

}

7.判断二叉树是否是完全二叉树

什么是完全二叉树呢?参见

booleanisCompleteTreeNode(TreeNode root){

if(root ==null){

returnfalse;

}

Queue queue =newLinkedList();

queue.add(root);

boolean result =true;

boolean hasNoChild =false;

while(!queue.isEmpty()){

TreeNode current = queue.remove();

if(hasNoChild){

if(current.left!=null||current.right!=null){

result =false;

break;

}

}else{

if(current.left!=null&¤t.right!=null){

queue.add(current.left);

queue.add(current.right);

}elseif(current.left!=null&¤t.right==null){

queue.add(current.left);

hasNoChild =true;

}elseif(current.left==null&¤t.right!=null){

result =false;

break;

}else{

hasNoChild =true;

}

}

}

returnresult;

}

8. 两个二叉树是否完全相同

booleanisSameTreeNode(TreeNode t1,TreeNode t2){

if(t1==null&&t2==null){

returntrue;

}

elseif(t1==null||t2==null){

returnfalse;

}

if(t1.val != t2.val){

returnfalse;

}

booleanleft = isSameTreeNode(t1.left,t2.left);

booleanright = isSameTreeNode(t1.right,t2.right);

returnleft&&right;

}

9. 两个二叉树是否互为镜像

booleanisMirror(TreeNode t1,TreeNode t2){

if(t1==null&&t2==null){

returntrue;

}

if(t1==null||t2==null){

returnfalse;

}

if(t1.val != t2.val){

returnfalse;

}

returnisMirror(t1.left,t2.right)&&isMirror(t1.right,t2.left);

}

10. 翻转二叉树or镜像二叉树

TreeNodemirrorTreeNode(TreeNode root){

if(root ==null){

returnnull;

}

TreeNode left = mirrorTreeNode(root.left);

TreeNode right = mirrorTreeNode(root.right);

root.left = right;

root.right = left;

returnroot;

}

11. 求两个二叉树的最低公共祖先节点

TreeNodegetLastCommonParent(TreeNode root,TreeNode t1,TreeNode t2){

if(findNode(root.left,t1)){

if(findNode(root.right,t2)){

returnroot;

}else{

returngetLastCommonParent(root.left,t1,t2);

}

}else{

if(findNode(root.left,t2)){

returnroot;

}else{

returngetLastCommonParent(root.right,t1,t2)

}

}

}

// 查找节点node是否在当前 二叉树中

booleanfindNode(TreeNode root,TreeNode node){

if(root ==null|| node ==null){

returnfalse;

}

if(root == node){

returntrue;

}

booleanfound = findNode(root.left,node);

if(!found){

found = findNode(root.right,node);

}

returnfound;

}

12. 二叉树的前序遍历

迭代解法

ArrayList preOrder(TreeNode root){

Stackstack=newStack();

ArrayListlist=newArrayList();

if(root == null){

returnlist;

}

stack.push(root);

while(!stack.empty()){

TreeNode node =stack.pop();

list.add(node.val);

if(node.right!=null){

stack.push(node.right);

}

if(node.left != null){

stack.push(node.left);

}

}

returnlist;

}

递归解法

ArrayListpreOrderReverse(TreeNode root){

ArrayList result =newArrayList();

preOrder2(root,result);

returnresult;

}

voidpreOrder2(TreeNode root,ArrayList<Integer> result){

if(root ==null){

return;

}

result.add(root.val);

preOrder2(root.left,result);

preOrder2(root.right,result);

}

13. 二叉树的中序遍历

ArrayList inOrder(TreeNode root){

ArrayListlist=newArrayList<();

Stackstack=newStack();

TreeNode current = root;

while(current != null|| !stack.empty()){

while(current != null){

stack.add(current);

current = current.left;

}

current =stack.peek();

stack.pop();

list.add(current.val);

current = current.right;

}

returnlist;

}

14.二叉树的后序遍历

ArrayList postOrder(TreeNode root){

ArrayListlist=newArrayList();

if(root ==null){

returnlist;

}

list.addAll(postOrder(root.left));

list.addAll(postOrder(root.right));

list.add(root.val);

returnlist;

}

15.前序遍历和后序遍历构造二叉树

TreeNodebuildTreeNode(int[] preorder,int[] inorder){

if(preorder.length!=inorder.length){

returnnull;

}

returnmyBuildTree(inorder,0,inorder.length-1,preorder,0,preorder.length-1);

}

TreeNodemyBuildTree(int[] inorder,intinstart,intinend,int[] preorder,intprestart,intpreend){

if(instart>inend){

returnnull;

}

TreeNode root =newTreeNode(preorder[prestart]);

intposition = findPosition(inorder,instart,inend,preorder[start]);

root.left = myBuildTree(inorder,instart,position-1,preorder,prestart+1,prestart+position-instart);

root.right = myBuildTree(inorder,position+1,inend,preorder,position-inend+preend+1,preend);

returnroot;

}

intfindPosition(int[] arr,intstart,intend,intkey){

inti;

for(i = start;i<=end;i++){

if(arr[i] == key){

returni;

}

}

return-1;

}

16.在二叉树中插入节点

TreeNodeinsertNode(TreeNode root,TreeNode node){

if(root == node){

returnnode;

}

TreeNode tmp =newTreeNode();

tmp = root;

TreeNode last =null;

while(tmp!=null){

last = tmp;

if(tmp.val>node.val){

tmp = tmp.left;

}else{

tmp = tmp.right;

}

}

if(last!=null){

if(last.val>node.val){

last.left = node;

}else{

last.right = node;

}

}

returnroot;

}

17.输入一个二叉树和一个整数,打印出二叉树中节点值的和等于输入整数所有的路径

voidfindPath(TreeNode r,inti){

if(root == null){

return;

}

Stackstack=newStack();

intcurrentSum =0;

findPath(r, i,stack, currentSum);

}

voidfindPath(TreeNode r,inti,Stackstack,intcurrentSum){

currentSum+=r.val;

stack.push(r.val);

if(r.left==null&&r.right==null){

if(currentSum==i){

for(intpath:stack){

System.out.println(path);

}

}

}

if(r.left!=null){

findPath(r.left, i,stack, currentSum);

}

if(r.right!=null){

findPath(r.right, i,stack, currentSum);

}

stack.pop();

}

18.二叉树的搜索区间

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

ArrayList result;

ArrayListsearchRange(TreeNode root,intk1,intk2){

result =newArrayList();

searchHelper(root,k1,k2);

returnresult;

}

voidsearchHelper(TreeNode root,intk1,intk2){

if(root ==null){

return;

}

if(root.val>k1){

searchHelper(root.left,k1,k2);

}

if(root.val>=k1&&root.val<=k2){

result.add(root.val);

}

if(root.val

searchHelper(root.right,k1,k2);

}

}

19.二叉树的层次遍历

ArrayList> levelOrder(TreeNode root){

ArrayList> result =newArrayList>();

if(root == null){

returnresult;

}

Queuequeue=newLinkedList();

queue.offer(root);

while(!queue.isEmpty()){

intsize =queue.size();

ArrayList< level =newArrayList():

for(inti =0;i < size ;i++){

TreeNode node =queue.poll();

level.add(node.val);

if(node.left != null){

queue.offer(node.left);

}

if(node.right != null){

queue.offer(node.right);

}

}

result.add(Level);

}

returnresult;

}

20.二叉树内两个节点的最长距离

二叉树中两个节点的最长距离可能有三种情况:

1.左子树的最大深度+右子树的最大深度为二叉树的最长距离

2.左子树中的最长距离即为二叉树的最长距离

3.右子树种的最长距离即为二叉树的最长距离

因此,递归求解即可

privatestaticclassResult{

intmaxDistance;

intmaxDepth;

publicResult(){

}

publicResult(intmaxDistance,intmaxDepth){

this.maxDistance = maxDistance;

this.maxDepth = maxDepth;

}

}

intgetMaxDistance(TreeNode root){

returngetMaxDistanceResult(root).maxDistance;

}

ResultgetMaxDistanceResult(TreeNode root){

if(root ==null){

Result empty =newResult(0,-1);

returnempty;

}

Result lmd = getMaxDistanceResult(root.left);

Result rmd = getMaxDistanceResult(root.right);

Result result =newResult();

result.maxDepth = Math.max(lmd.maxDepth,rmd.maxDepth) +1;

result.maxDistance = Math.max(lmd.maxDepth + rmd.maxDepth,Math.max(lmd.maxDistance,rmd.maxDistance));

returnresult;

}

21.不同的二叉树

给出 n,问由 1…n 为节点组成的不同的二叉查找树有多少种?

intnumTrees(intn ){

int[] counts =newint[n+2];

counts[0] =1;

counts[1] =1;

for(inti =2;i<=n;i++){

for(intj =0;j

counts[i] += counts[j] * counts[i-j-1];

}

}

returncounts[n];

}

22.判断二叉树是否是合法的二叉查找树(BST)

一棵BST定义为:

节点的左子树中的值要严格小于该节点的值。

节点的右子树中的值要严格大于该节点的值。

左右子树也必须是二叉查找树。

一个节点的树也是二叉查找树。

publicintlastVal = Integer.MAX_VALUE;

publicbooleanfirstNode =true;

publicbooleanisValidBST(TreeNode root){

// write your code here

if(root==null){

returntrue;

}

if(!isValidBST(root.left)){

returnfalse;

}

if(!firstNode&&lastVal >= root.val){

returnfalse;

}

firstNode =false;

lastVal = root.val;

if(!isValidBST(root.right)) {

returnfalse;

}

returntrue;

}

深刻的理解这些题的解法思路,在面试中的二叉树题目就应该没有什么问题,甚至可以怼他,哈哈。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容

  • 1.HashMap是一个数组+链表/红黑树的结构,数组的下标在HashMap中称为Bucket值,每个数组项对应的...
    谁在烽烟彼岸阅读 994评论 2 2
  • 上次写了二叉树遍历,其中在非递归的遍历中,只写了前序遍历,没有写非递归中序遍历和后续遍历。非递归要用到栈,只要根据...
    BrianAguilar阅读 437评论 0 1
  • 感恩父母养育之恩,感恩天地万物滋养。 感恩师父的课程。 好的儿子一起共进午餐。 感恩老师的中医课。 感恩纽约小龙女...
    演权阅读 214评论 0 3
  • 你因你之所是而有权获得奇迹。你因上帝之所是而会收到奇迹。你会因你与上帝合一而给与奇迹。再说一遍,得救是多么简单!它...
    A000珠珠阅读 274评论 0 1
  • 大家晚上好,我是临沂圣昊的许文峰。 今天是我日精进第252天,跟大家分享我今天的感悟和成长,每天进步一点点,距离成...
    IiftSky阅读 123评论 0 0