这题参考了Code Ganker大牛思路
http://blog.csdn.net/linhuanmars/article/details/23717703
设置pre结点,每次pre左结点设置为空,右结点设置为当前结点。有一点特别要注意的是Java是pass by value,所以需要用一个单元素的TreeNode数组来储存并且改值。
- ArrayList<TreeNode> pre = new ArrayList<TreeNode>();
- public void flatten(TreeNode root) {
- pre.add(null);
- helper(root);
- }
- private void helper(TreeNode root)
- {
- if(root == null)
- return;
- TreeNode right = root.right;
- if(pre.get(0)!=null)
- {
- pre.get(0).left = null;
- pre.get(0).right = root;
- }
- pre.set(0,root);
- helper(root.left);
- helper(right);
- }