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 }

 

 posted on 2014-05-02 10:46  zhuli19901106  阅读(713)  评论(0)    收藏  举报