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的节点,如果找不到,就说明没法下沉了;否则继续下沉。
代码:
// http://www.careercup.com/question?id=5344154741637120
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
using namespace std; struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val = ): val(_val), left(nullptr), right(nullptr) {};
}; void constructBinaryTree(TreeNode *&root)
{
static string s;
stringstream sio;
int val; if (cin >> s && s == "#") {
root = nullptr;
} else {
sio << s;
if (sio >> val) {
root = new TreeNode(val);
constructBinaryTree(root->left);
constructBinaryTree(root->right);
} else {
root = nullptr;
}
}
} void preorderTraversal(TreeNode *root)
{
if (root == nullptr) {
cout << "# ";
} else {
cout << root->val << ' ';
preorderTraversal(root->left);
preorderTraversal(root->right);
}
} class Solution {
public:
void sinkZero(TreeNode *root) {
if (root == nullptr) {
return;
} if (root->val == ) {
TreeNode *ptr = findNonZeroNode(root); if (ptr != nullptr) {
swap(root->val, ptr->val);
} else {
// all zero, no need to go down any more.
return;
}
}
sinkZero(root->left);
sinkZero(root->right);
};
private:
TreeNode *findNonZeroNode(TreeNode *root) {
if (root == nullptr) {
return root;
} else if (root->val != ) {
return root;
} else {
TreeNode *ptr = findNonZeroNode(root->left);
if (ptr != nullptr) {
return ptr;
} else {
return findNonZeroNode(root->right);
}
}
};
}; int main()
{
TreeNode *root;
Solution sol; while (true) {
constructBinaryTree(root);
if (root == nullptr) {
break;
}
sol.sinkZero(root);
preorderTraversal(root);
cout << endl;
} return ;
}