将一颗二叉树展开为链表
程序员文章站
2022-05-21 19:26:20
...
题目描述:
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode cur = null;
public void flatten(TreeNode root) {
if(root == null) {
return;
}
if(cur != null) {
cur.right = root;
cur.left = null;
}
cur = root;//cur节点向右子树移动
//由于cur节点只记录右子树,类似回溯手段,需要重新拷贝一份进行递归
TreeNode copyRight = root.right;
flatten(root.left);
flatten(copyRight);
//flatten(root.right);
}
}