操作给定的二叉树,将其变换为源二叉树的镜像。
数据范围:二叉树的节点数
, 二叉树每个节点的值
要求: 空间复杂度
。本题也有原地操作,即空间复杂度
的解法,时间复杂度
比如:
源二叉树
镜像二叉树
function Mirror( pRoot ) { // write code here if(!pRoot) return null else{ //先进行交换 ,在进行递归 [pRoot.right,pRoot.left]=[pRoot.left,pRoot.right] Mirror(pRoot.right) Mirror(pRoot.left) } return pRoot }
function Mirror( pRoot ) { // write code here if(pRoot == null) return pRoot; let queue = []; queue.push(pRoot); while(queue.length!==0){ let node = queue.shift(); //交换当前节点的左右子树 if(node!==null){ let tmp = node.right; node.right = node.left; node.left = tmp; queue.push(node.left); queue.push(node.right); } } return pRoot; }
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return TreeNode类 */ function Mirror( pRoot ) { if(pRoot){ let left = pRoot.left; let right = pRoot.right; if(left || right){ pRoot.right = left; pRoot.left = right; if(left) Mirror(left); if(right) Mirror(right) } } return pRoot } module.exports = { Mirror : Mirror };
/* * function TreeNode(x) { * this.val = x; * this.left = null; * this.right = null; * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return TreeNode类 */ function Mirror( pRoot ) { if(pRoot === null) return null; let arr = []; arr.push(pRoot); while(arr.length > 0) { let node = arr.pop(); let nodeLeft = node.left; node.left = node.right; node.right = nodeLeft; if(node.left) arr.push(node.left); if(node.right) arr.push(node.right); } return pRoot; } module.exports = { Mirror : Mirror };
function Mirror( pRoot ) { if(!pRoot) return null; let nodeLeft = pRoot.left; pRoot.left = pRoot.right; pRoot.right = nodeLeft; Mirror(pRoot.left); Mirror(pRoot.right); return pRoot; }
function Mirror( pRoot ) { if(!pRoot) { return null; } let temp = new TreeNode(0); temp = pRoot.left; pRoot.left = pRoot.right; pRoot.right = temp; Mirror(pRoot.left); Mirror(pRoot.right); return pRoot; }
function Mirror( pRoot ) { // write code here if(!pRoot){ return } Mirror(pRoot.left) Mirror(pRoot.right) let temp=pRoot.left pRoot.left=pRoot.right pRoot.right=temp return pRoot }
function Mirror( pRoot ) { // write code here if(pRoot == null){ return pRoot; } // var temp = pRoot.left; // pRoot.left = pRoot.right; // pRoot.right = temp; [pRoot.left,pRoot.right] = [pRoot.right,pRoot.left]; Mirror(pRoot.left); Mirror(pRoot.right); return pRoot; }
function Mirror( pRoot ) { if(pRoot==null) return null nodeChange(pRoot) return pRoot } function nodeChange(root){ if(root.left==null && root.right==null) return var temp=root.left root.left=root.right root.right=temp if(root.left!==null) nodeChange(root.left) if(root.right!==null) nodeChange(root.right) }