Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
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 prev = null;
public void flatten(TreeNode root) {
if(root == null)
return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;//记录下来
}
}
/**
explantion:
由于该树为二叉搜索树,所以我们知道当其变为斜树时,其最大子结点也在最右端。所以其最大值子结点位于该树的最右端,所以需要先遍历其右子树,找到该结点。将其left跟right均设为null值。最后将该结点记录下来。方便将该结点代表的子树作为上一层结点的右子树。而对于原来树的左子树,我们知道其最左端结点,一定为斜树的根,所以遍历完右子树,才对左子树进行遍历。
**/