簡單題,判斷好每種狀況,(原來劍指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刪除遍歷的元素,其實不必。本身控制邊界點便可。this
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));