[LintCode] 翻转二叉树

简介: 递归实现: 1 /** 2 * Definition of TreeNode: 3 * class TreeNode { 4 * public: 5 * int val; 6 * TreeNode *left, *right; 7 * ...

递归实现:

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param root: a TreeNode, the root of the binary tree
17      * @return: nothing
18      */
19     void invertBinaryTree(TreeNode *root) {
20         // write your code here
21         if (!root) return;
22         swap(root -> left, root -> right);
23         invertBinaryTree(root -> left);
24         invertBinaryTree(root -> right);
25     }
26 };

迭代实现:

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 class Solution {
14 public:
15     /**
16      * @param root: a TreeNode, the root of the binary tree
17      * @return: nothing
18      */
19     void invertBinaryTree(TreeNode *root) {
20         // write your code here
21         if (!root) return;
22         queue<TreeNode*> level;
23         level.push(root);
24         while (!level.empty()) {
25             TreeNode* node = level.front();
26             level.pop();
27             swap(node -> left, node -> right);
28             if (node -> left) level.push(node -> left);
29             if (node -> right) level.push(node -> right);
30         }
31     }
32 };

 

目录
相关文章
|
8月前
力扣226:翻转二叉树
力扣226:翻转二叉树
41 0
|
8月前
|
Java C++ Python
leetcode-226:翻转二叉树
leetcode-226:翻转二叉树
32 0
Leetcode226.翻转二叉树
Leetcode226.翻转二叉树
44 0
leetcode(翻转二叉树)
leetcode(翻转二叉树)
48 0
|
1月前
leecode刷题 翻转二叉树
给定一棵二叉树的根节点 `root`,翻转这棵二叉树并返回其根节点。通过递归交换每个节点的左右子树来实现翻转。示例 1:输入 `root = [4,2,7,1,3,6,9]`,输出 `[4,7,2,9,6,3,1]`。示例 2:输入 `root = [2,1,3]`,输出 `[2,3,1]`。示例 3:输入 `root = []`,输出 `[]`。树中节点数目范围在 [0, 100] 内,节点值范围为 -100 到 100。
|
8月前
[LeetCode]—— 226——翻转二叉树
[LeetCode]—— 226——翻转二叉树
LeetCode | 226. 翻转二叉树
LeetCode | 226. 翻转二叉树
|
8月前
|
存储 算法
算法题解-翻转二叉树
算法题解-翻转二叉树
|
存储 算法
每日刷题(翻转+二分+BFS)
每日刷题(翻转+二分+BFS)