Leetcode中几道二叉树题 III

三、树的层次/序列化

题目一: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;
        }
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值