反转二叉树
来源:互联网 发布:java合并两个集合 编辑:程序博客网 时间:2024/05/22 07:47
Invert a binary tree:
4 / \ 2 7 / \ / \1 3 6 9to
4 / \ 7 2 / \ / \9 6 3 1Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
<pre name="code" class="plain">/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
递归版:
struct TreeNode* invertTree(struct TreeNode* root){ struct TreeNode *node;if (root == NULL)return root;node = invertTree(root->left);root->left = invertTree(root->right);root->right = node;return root;}
非递归版:
struct TreeNode* invertTree(struct TreeNode *root){struct TreeNode *node, *tmp;Stack treeStack;if (root == NULL)return root;stack_init(&treeStack, NULL);stack_push(&treeStack, root);while (treeStack.size > 0){stack_pop(&treeStack, &node);tmp = node->left;node->left = node->right;node->right = tmp;if (node->left)stack_push(&treeStack, node->left);if (node->right)stack_push(&treeStack, node->right);}stack_destory(&treeStack);return root;}
0 0
- 反转二叉树
- 二叉树反转
- 反转二叉树,哈哈
- 反转二叉树
- 二叉树反转
- 二叉树反转
- 二叉树--反转
- 反转二叉树
- 反转二叉树
- 反转二叉树
- 反转二叉树
- 二叉树的反转
- 反转二叉树
- LeetCode:反转二叉树
- 反转二叉树
- 反转二叉树
- 反转二叉树
- java 反转二叉树算法
- leetcode--Maximum Product Subarray
- Python包管理工具——Pip
- Android数据库Sqlite中索引的使用
- hdu 1398 Square Coins
- IE主页被篡改(试验通过)
- 反转二叉树
- 浅谈tomcat之apache-maven
- shell学习二十一天----重新格式化段落
- 标准差和标准误差的区别
- 对常用的安全性测试的总结(以后会陆续更新)_Phoenix-晶
- hibernate缓存的学习
- 剑指offer--旋转数组的最小数字
- vsftpd
- std::vector的几种遍历方式比较