剑指offer(十七,十八,十九)树的子结构,二叉树的镜像,顺时针打印矩阵

简单题,判断好每种情况,(原来剑指offer这个oj需要把js的函数写在给的solution函数里才能AC啊)

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */

function HasSubtree(pRoot1, pRoot2)
{ 
    // write code here
    if(pRoot1 !== null && pRoot2 !== null) {
        if( judge(pRoot1,pRoot2) ){ 
            return true;
        }else {
            return HasSubtree(pRoot1.left,pRoot2) || HasSubtree(pRoot1.right,pRoot2)
        }
    }else {
        return false
    }
     function judge(p1, p2) {
        if(p2===null) return true;
        if(p1===null) return false;
        if(p1.val !== p2.val )return false; 
        return judge(p1.left,p2.left)&&judge(p1.right,p2.right);
    }
}

传说中的毒瘤题,曾经的一个大佬去google面试时现场没写出来,被google说滚蛋。。。
其实很简单,老样子树结构判断好null

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Mirror(root)
{
    if(root) {
      var tmp = root.left;
      root.left = root.right;
      root.right = tmp;
      if(root.left) {
        Mirror(root.left);
      }
      if(root.right) {
        Mirror(root.right);
      }
    }
}
module.exports = {
    Mirror : Mirror
};

之前就遇到别人讨论过这题,今天碰到这题也格外的亲切,一种很好的思路:控制好要打印的矩形边界,遍历即可,一个矩形可由左上点和又下角的点确定(最近做的一个项目就遇到画矩形相关)。一开始时时打算每次直接暴力遍历矩形边,遍历完一次外边界后用splice删除遍历的元素,其实没必要。自己控制边界点即可。

function printMatrix(matrix)
{
    var row = matrix.length;
    var col = matrix[0].length;
    if(row===0||col===0) return null;
    row--;
    col--;
    var ans = [];
    //定义好左上点和右下点,把矩阵建立以左上点为坐标
    let left = 0,top = 0,right = col,bottom = row;
    while(left <= right && top <= bottom) {
      //四个循环,分别控制顶层,右边界,底层,左边界的遍历
      //现在是上边界,从左到右
      for(let i = left; i<=right; i++) {
        ans.push(matrix[top][i]);
      }
      //现在到达了右边界,从上到下
      for(let i = top+1; i<=bottom; i++) {
        ans.push(matrix[i][right]);
      }
      //现在到了下边界,从右到左
      if(bottom>top) {//防止单行重复遍历
        for(let i = right-1; i>=left; i--) {
          ans.push(matrix[bottom][i]);
        }
    }
      //现在到了左边界,从下往上
      if(right>left){//防止单列重复遍历
        for(let i = bottom-1; i>top; i--) {//注意这里不能等于,起点肯定是被push了的
          ans.push(matrix[i][left]);
        }
    }
      //控制边界
      left++,top++,right--,bottom--;
    }
    return ans;
}
var matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]];
console.log(printMatrix(matrix));

猜你喜欢

转载自www.cnblogs.com/zhangmingzhao/p/9106371.html