逆转二叉树
逆转二叉树 代码练手
#include <iostream> #include <memory> using namespace std; struct TreeNode{ int val; shared_ptr<TreeNode> left; shared_ptr<TreeNode> right; }; void PrintTree(shared_ptr<TreeNode> root) { if (!root) return; cout << root->val << " "; PrintTree(root->left); PrintTree(root->right); return; } shared_ptr<TreeNode> CreateNode(int i) { shared_ptr<TreeNode> p(new TreeNode()); p->val = i; return p; } void InsertNode(shared_ptr<TreeNode>& root,int i) { if (!root) { root = CreateNode(i); return; } if (i > root->val) { InsertNode(root->right, i); } else if (i < root->val) { InsertNode(root->left, i); } else if (i == root->val) return; return; } shared_ptr<TreeNode> InvertTree(shared_ptr<TreeNode>& root ) { if (!root) return root; shared_ptr<TreeNode> tmp = root->left; root->left = InvertTree(root->right); root->right = InvertTree(tmp); return root; } int main() { shared_ptr<TreeNode> root = CreateNode(4); InsertNode(root, 2); InsertNode(root, 7); InsertNode(root, 1); InsertNode(root, 3); InsertNode(root, 6); InsertNode(root, 9); PrintTree(root); InvertTree(root); cout << endl; PrintTree(root); return 0; }
输出:
4 2 1 3 7 6 9
4 7 9 6 2 3 1
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力