题目描述
方法一;递归
//方法二:递归
class Solution {
public void flatten(TreeNode root) {
if (root == null) {
return;
}
flatten(root.left);
flatten(root.right);
//到这里,按照结果来看,左右子树已经被捋成链表了,下面的只是逻辑,对于递归末端和上面任何一层都适用
//写的时候就不需要再想末端情况了,直接想一种简单情况来搞通逻辑就行
TreeNode tmp = root.right;
root.right = root.left;//新的右子树为:把之前的左子树捋直了
root.left = null;//新的左子树为null
//找到新的右子树的末端
TreeNode cur = root;
while (cur.right != null) {
cur = cur.right;
}
cur.right = tmp;//找到新的右子树的末端后,把捋直了的之前的右子树接上
}
}
方法二:迭代
- 前序遍历整棵树,把每个节点添加到list中
- 从list中逐个取出节点添加到root.right
迭代版
class Solution {
public void flatten(TreeNode root) {
if (root == null) return; //特判
Stack<TreeNode> stack = new Stack<>();
List<TreeNode> list = new ArrayList<>();//存放前序遍历节点
TreeNode node = root;
//迭代,前序遍历
while (node != null || !stack.isEmpty()) {
if (node != null) {
stack.push(node);
list.add(node);
node = node.left;
} else {
TreeNode father = stack.pop();
node = father.right;
}
}
//往root的right逐个添加节点
root = list.get(0);
TreeNode cur = root;
for (int i = 1; i < list.size(); i++) {
cur.right = list.get(i);
cur.left = null;
cur = cur.right;
}
}
}
递归版
class Solution {
public void flatten(TreeNode root) {
if(root == null) {
return;//妈了个巴子,谁他妈没事干输入[]
}
List<TreeNode> list = new ArrayList<>();
dfs(root, list);
root = list.get(0);
for (int i = 1; i < list.size(); i++) {
root.right = list.get(i);
root.left = null;//这个题需要将left置null
root = root.right;
}
}
public void dfs(TreeNode node, List<TreeNode> list) {
if (node == null) {
return;
}
list.add(node);
dfs(node.left, list);
dfs(node.right, list);
}
}