2023.10.22
本题第一反应就是将 原二叉树的节点值 用先序遍历的方式保存到一个集合数组中。然后再重新构造出新的二叉树。 java代码如下:
java
/**
* 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 {
private List<Integer> list = new ArrayList<>();
private void preTravelsal(TreeNode cur){
if(cur == null) return;
list.add(cur.val);
preTravelsal(cur.left);
preTravelsal(cur.right);
}
public void flatten(TreeNode root) {
if(root == null) return;
preTravelsal(root);
for(int i=1; i<list.size(); i++){
root.right = new TreeNode(list.get(i));
root.left = null;
root = root.right;
}
}
}