Java教程

剑指 Offer 27. 二叉树的镜像

本文主要是介绍剑指 Offer 27. 二叉树的镜像,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

方法一 递归

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {TreeNode}
11  */
12 var mirrorTree = function(root) {
13     if(root == null) return root;
14     let temp = root.left;
15     root.left = mirrorTree(root.right);
16     root.right = mirrorTree(temp);
17     return root;
18 };

方法二 栈

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {TreeNode}
11  */
12 var mirrorTree = function(root) {
13     if(root == null) return null;
14     let stack = [root];
15     while(stack.length > 0) {
16         const tem = stack.pop();
17         if(tem.left) {
18             stack.push(tem.left);
19         }
20         if(tem.right) {
21             stack.push(tem.right);
22         }
23         const temp = tem.left;
24         tem.left = tem.right;
25         tem.right = temp;
26     }
27     return root;
28 };

 

这篇关于剑指 Offer 27. 二叉树的镜像的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!