Given a binary tree, flatten it to a linked list in-place.
For example,
Given
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; } * } */ public class Solution { public void flatten(TreeNode root) { if( root == null) return ; else if( root.left == null ) flatten(root.right); else{ TreeNode node = root.right; TreeNode node2 = getRight(root.left); root.right = root.left; root.left = null; node2.right = node; flatten(root.right); } } public TreeNode getRight(TreeNode root ){ while( root.right != null) root = root.right; return root; } }