114. 二叉树展开为链表
114. 二叉树展开为链表
题目:
题解:
/** * 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) { while(root != null) { //左子树为null,直接考虑下一节点 if(root.left == null) { root = root.right; } else { //找到左子树最右边的结点 TreeNode pre = root.left; while(pre.right != null) { pre = pre.right; } //将原来的右子树接到左子树的最右边结点 pre.right = root.right; root.right = root.left; root.left = null; root = root.right; } } } }