Flatten Binary Tree to Linked List

来源:互联网 发布:淘宝网货到付款 编辑:程序博客网 时间:2024/05/18 03:16

题目描述:

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
非递归方法如下:

public void flatten(TreeNode root){      while(root!=null){      System.out.println("root:"+root.val);        if(root.left!=null){             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;      }  }  

2种递归方法

第一个方法在rootnode上直接操作,先暂时保存左右子树,如果root有左子树,把root.right赋值为root.left,root.left赋值为null,再在已经是右子树的左子树上找rightmost的node,把之前存住的right子树放在rightmost.right上即可。做完一遍以后,这时root的左子树已经已经被嫁接到了右子树和root之间,原来的左子树变成null,可以进行root.right的递归了。

代码如下:

public class Solution {    public void flatten(TreeNode root) {        if(root == null)             return;        if(root.left != null){            TreeNode left = root.left;            TreeNode right = root.right;            root.left = null;            root.right = left;            TreeNode rightMost = root.right;            while(rightMost.right != null){                 rightMost = rightMost.right;            }            rightMost.right = right;        }        flatten(root.right);    }}

第2种方法对二叉树进行前序遍历,把每次找到的节点加到链表的前一个节点。
注意要用一个一元数组,这样才能保证里面的当前节点的上一个节点是先序遍历的前一个节点而不是父节点。

这个和recover binary search tree比较,那个题pre是全局变量,所以可以那样做!

代码如下:

public class Solution {     public void flatten_re(TreeNode root, TreeNode[] current) {          if(root==null) {              return;          }          TreeNode left  = root.left;          TreeNode right = root.right;          if(left!=null) {              root.left = null;          }          current[0].right = root;          current[0] = root;          if(left!=null) {              flatten_re(left,current);          }          if(root.right!=null) {              flatten_re(right,current);          }          return;      }            public void flatten(TreeNode root) {          if(root==null) {              return;          }          if(root.left==null&&root.right==null) {              return;          }          TreeNode [] array = new TreeNode[1];          array[0] = root;          flatten_re(root,array);          return;      }  }

0 0
原创粉丝点击