Leetcode Daily Brush Question Tree (2) 114 Binary Tree Expands into Linked List

Preface

I learned JAVA for a day today. In the last hour of today, I will write a tree problem. I learned this topic from Dongge, and then record it now. I hope I will learn all the methods tomorrow.

Binary tree expands into linked list

Insert picture description here

Title description

Insert picture description here

Problem analysis

The idea is to first turn the left subtree into a linked list, then turn the right one into a linked list, and finally insert the right one to the end of the left subtree linked list.

Implementation code

class Solution {
    
    
    public void flatten(TreeNode root) {
    
    
        if(root == null){
    
    
            return;
        }
        //将左子树拉成链表
        flatten(root.left);
        //将右子树拉成链表
        flatten(root.right);
        //定义一个指针用来指向左子树的头
        TreeNode left = root.left;
        //定义一个指针用来指向左子树的头
        TreeNode right = root.right;
        //清空根节点的左子树,因为我们要整成链表
        root.left = null;
        root.right = left;
        TreeNode p =root;
        //遍历到链表尾部
        while(p.right!=null){
    
    
            p = p.right;
        } 
        //将右子树接到左子树上面
        p.right = right;
        
    }
}

to sum up

Guess you like

Origin blog.csdn.net/tan45du_yuan/article/details/108784248