Leetcode中几道二叉树题 III

来源:互联网 发布:qq人肉搜索软件 编辑:程序博客网 时间:2024/06/05 02:21

三、树的层次/序列化

题目一:Populating Next Right Pointers in Each Node

Given a binary tree, populating each next pointer to pointer to its right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

思路:必须通过层次访问二叉树,建立每一层节点之间的连接。

class Solution {public:    void connect(TreeLinkNode *root) {        if(root==NULL) return;        vector<TreeLinkNode*> q;        q.push_back(root);        int cur=0;        while(cur<q.size()){            int last=q.size();            while(cur<last){                if(cur<last-1){                    q[cur]->next=q[cur+1];                }                else q[cur]->next=NULL;                if(q[cur]->left) q.push_back(q[cur]->left);                if(q[cur]->right) q.push_back(q[cur]->right);                cur++;            }        }    }};


题目二:Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work?

思路:对解题方法没有任何影响。


题目三:Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place. Hints: if you notice carefully in the flattened tree, each node's right child pointers to the next node of a pre-order traversal. 

思路1:因为是跟先序遍历与关系,那么只需要改造先序遍历,即可得到一个解。

class Solution {public:    void flatten(TreeNode *root) {        if(root==NULL) return;        last=NULL;        preOrderFlatten(root);    }        void preOrderFlatten(TreeNode *root){        if(root==NULL) return;        TreeNode *savedRight=root->right; //先保存根节点的右孩子节点        if(last==NULL)             last=root;        else{             last->right=root;            last->left=NULL;        }        last=root;        preOrderFlatten(root->left);        preOrderFlatten(savedRight);  //由于遍历改变root->right的值,故这里需先保存    }private:    TreeNode *last;   //保存上次访问的节点};
说明:这种解法不同与一般的遍历,因为它在遍历中改变了数的结构,因此需要提前保存好被改变的部分!


思路2:原题实质要求的是in-place解法,所以上面的解法并不是很符合要求,因此还得使用一般的“模拟”遍历。

class Solution {public:    void flatten(TreeNode *root) {        if(root==NULL) return;                while(root){            if(root->left){                TreeNode *rightMost=root->left;                while(rightMost->right)                    rightMost=rightMost->right;                rightMost->right=root->right;                                root->right=root->left;  //事先已经保存好了                root->left=NULL;            }            root=root->right;        }    }};



0 0
原创粉丝点击