15算法课程 226. Invert Binary Tree
来源:互联网 发布:俞兆林内裤怎么样知乎 编辑:程序博客网 时间:2024/06/16 15:26
Invert a binary tree.
4 / \ 2 7 / \ / \1 3 6 9
- 1
- 2
- 3
- 4
- 5
- 6
![](http://static.blog.csdn.net/images/save_snippets.png)
to
4 / \ 7 2 / \ / \9 6 3 1
- 1
- 2
- 3
- 4
- 5
- 6
![](http://static.blog.csdn.net/images/save_snippets.png)
Solution
用递归算法解决,首先交换根节点的左右子树,再对左右子树递归交换。
递归的终止条件是当前节点为NULL
Code
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* invertTree(TreeNode* root) { if (!root) return root; TreeNode * tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; }};
阅读全文
0 0
- 15算法课程 226. Invert Binary Tree
- 226.Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- 226. Invert Binary Tree
- poj3195 Generalized Matrioshkas(栈)
- Ubuntu上离线安装包的制作与安装
- Camera Calibration calibrateCamera()
- 解决dubbo的vc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for
- 如何将python3.6软件的py文件打包成exe程序
- 15算法课程 226. Invert Binary Tree
- C#简单依赖注入解析类
- C语言之unsigned char和uint8_t
- hdu1272(基础并查集)
- # prototype和__proto__分析
- 利用反向传播训练多层神经网络的原理
- 华为笔试题(7)
- phpmyadmin 1146
- web测试的思考