LeetCode114.二叉树展开为链表(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 {
public void flatten(TreeNode root) {
if(root == null || (root.left == null && root.right == null)) return;
//记录右节点
TreeNode right = null;
if(root.right != null) right = root.right;
//将左节点移到右节点上来
root.right = root.left;
root.left = null;
//找到现在的最右边的叶子节点(原来左节点的最右边的叶子节点)
TreeNode cur = root;
while(cur != null && cur.right != null) {
cur = cur.right;
}
//将记录的右节点连接到该叶子节点的右节点上
cur.right = right;
//递归处理根节点的右节点
flatten(root.right);
}
}
作者:oyzg(醉笙)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/114er-cha-shu-zhan-kai-wei-lian-biao-jav-khb9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。