首页 > 代码库 > leetcode -- Flatten Binary Tree to Linked List

leetcode -- Flatten Binary Tree to Linked List

算法:

1. 对root的左子树做处理,让左子树的根节点作为,根节点的右子树,并让右子树作为左子树根节点的右子树的子树

2. 递归遍历右子树

public void flatten(TreeNode root) {
        if(root==null){
            return;
        }
        if(root.left!=null){
            TreeNode leftNode=root.left;
            TreeNode rightNode=root.right;
            root.left=null;
            root.right=leftNode;
            TreeNode tmp=leftNode;//root.left has been null
            while(tmp.right!=null){
                tmp=tmp.right;
            }
            tmp.right=rightNode;
        }
        flatten(root.right);
    }