思路
深度优先遍历:首先将二叉树进行前序遍历,将每个遍历的节点存入一个链表当中
解题过程
将链表还原为只有右子树的二叉树即可
Code
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {List<TreeNode> list=new ArrayList<>();public void flatten(TreeNode root) {dfs(root);for(int i=0;i<list.size()-1;i++){TreeNode t=list.get(i);t.left=null;t.right=list.get(i+1);}}public void dfs(TreeNode root){if(root==null) return;list.add(root);dfs(root.left);dfs(root.right);}
}作者:菜卷
链接:https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/solutions/2953239/er-cha-shu-zhan-kai-wei-lian-biao-by-ash-dqd4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。