DFS+二叉树

103 阅读2分钟

参考大佬的刷题专题:blog.csdn.net/qq_45704942… 自己练习一遍做个记录~

二叉树的最大深度【力扣104】

自顶向下

深度优先遍历,从根节点开始,每次走到叶子结点时判断当前所在叶子的深度depth是否大于当前最大叶子深度ans,如果大于则更新当前最大叶子深度ans,所有路径遍历完后得到的最大叶子深度即二叉树的最大深度

let ans=0;
var topToBottom=function(root,depth){
    if(!root) return;
    if(!root.left&&!root.right) ans=Math.max(ans,depth);
    topToBottom(root.left,depth+1);
    topToBottom(root.right,depth+1);
}
var maxDepth = function(root) {
    topToBottom(root,1);
    let res=ans;
    ans=0;
    return res;
};

自底向上

最大树深=最大子树深+1

var maxDepth = function(root) {
    if(!root) return 0;
    else return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
};

对称二叉树【力扣101】

@2(}U9A(U${RLGQVF5~H8Z7.png

对称二叉树:

  • 空树或只有根结点的树
  • 根结点左右子树成镜像的树 成镜像的两棵树应该满足:
  • 两棵树的根结点相等或均为空
  • 左边树的左子树与右边树的右子树成镜像
  • 右边树的左子树与左边树的右子树成镜像
var isMirror=function(left,right){
    if(!left&&!right) return true;
    else if(!left||!right) return false;
    else{
        if(left.val!=right.val) return false;
    }
    return isMirror(left.left,right.right)&&isMirror(left.right,right.left);
}
var isSymmetric = function(root) {
    if(!root) return true;
    else return isMirror(root.left,root.right);
};

路径总和 【力扣112】

输入: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
输出: true

image.png

var hasPathSum = function(root, targetSum) {
    if(!root) return false;
    if(!root.left&&!root.right) return root.val===targetSum;
    else return hasPathSum(root.left,targetSum-root.val)||hasPathSum(root.right,targetSum-root.val);
};

二叉树的直径【力扣543】

image.png

任意一条路径均可以被看作由某个节点为起点,从其左儿子和右儿子向下遍历的路径拼接得到。
因此二叉树的直径=左子树深度+右子树深度的最大值=最长路径中路过的结点数-1

var diameterOfBinaryTree = function(root) {
    var depth=function(root){
    if(!root) return 0;
    let leftDepth=depth(root.left);
    let rightDepth=depth(root.right);
    nodesLength=Math.max(leftDepth+rightDepth+1,nodesLength);//每个结点的左右子树深度之和+自身1=经过该结点连接的最长路径路过的结点数
    return Math.max(leftDepth,rightDepth)+1;
    }
    if(!root) return 0;
    let nodesLength=1;
    depth(root);
    return nodesLength-1;//路径长度等于结点数-1
};

求根结点到叶结点数字之和【力扣129】

image.png

var sumNumbers = function(root) {
  var overNumbers=function(root,fatherTemp){
      if(!root) return 0;
      let temp=fatherTemp*10+root.val;
      if(!root.left&&!root.right) return temp;
      return overNumbers(root.left,temp)+overNumbers(root.right,temp);
  }
  return overNumbers(root,0);
};