2014-05-02 10:40
原题:
Sink Zero in Binary Tree. Swap zero value of a node with non-zero value of one of its descendants so that no node with value zero could be parent of node with non-zero.
题目:把二叉树中的值为0的节点尽量往下沉,保证所有值为0的节点绝不会有非0的子节点。
解法:我写的算法是O(n^2)的,对于每个值为0的节点,都向下寻找值为非0的节点,如果找不到,就说明没法下沉了;否则继续下沉。
代码:
1 // http://www.careercup.com/question?id=5344154741637120 2 #include <algorithm> 3 #include <iostream> 4 #include <sstream> 5 #include <string> 6 using namespace std; 7 8 struct TreeNode { 9 int val; 10 TreeNode *left; 11 TreeNode *right; 12 TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {}; 13 }; 14 15 void constructBinaryTree(TreeNode *&root) 16 { 17 static string s; 18 stringstream sio; 19 int val; 20 21 if (cin >> s && s == "#") { 22 root = nullptr; 23 } else { 24 sio << s; 25 if (sio >> val) { 26 root = new TreeNode(val); 27 constructBinaryTree(root->left); 28 constructBinaryTree(root->right); 29 } else { 30 root = nullptr; 31 } 32 } 33 } 34 35 void preorderTraversal(TreeNode *root) 36 { 37 if (root == nullptr) { 38 cout << "# "; 39 } else { 40 cout << root->val << ' '; 41 preorderTraversal(root->left); 42 preorderTraversal(root->right); 43 } 44 } 45 46 class Solution { 47 public: 48 void sinkZero(TreeNode *root) { 49 if (root == nullptr) { 50 return; 51 } 52 53 if (root->val == 0) { 54 TreeNode *ptr = findNonZeroNode(root); 55 56 if (ptr != nullptr) { 57 swap(root->val, ptr->val); 58 } else { 59 // all zero, no need to go down any more. 60 return; 61 } 62 } 63 sinkZero(root->left); 64 sinkZero(root->right); 65 }; 66 private: 67 TreeNode *findNonZeroNode(TreeNode *root) { 68 if (root == nullptr) { 69 return root; 70 } else if (root->val != 0) { 71 return root; 72 } else { 73 TreeNode *ptr = findNonZeroNode(root->left); 74 if (ptr != nullptr) { 75 return ptr; 76 } else { 77 return findNonZeroNode(root->right); 78 } 79 } 80 }; 81 }; 82 83 int main() 84 { 85 TreeNode *root; 86 Solution sol; 87 88 while (true) { 89 constructBinaryTree(root); 90 if (root == nullptr) { 91 break; 92 } 93 sol.sinkZero(root); 94 preorderTraversal(root); 95 cout << endl; 96 } 97 98 return 0; 99 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)