Flatten Binary Tree to Linked List

来源:互联网 发布:帝王三国破解版无网络 编辑:程序博客网 时间:2024/06/03 21:48

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

思路一: 根据提供的线索可以观察到,每一个结点的右指针都指向它前序遍历的后一个结点。那么我们可以维持一个全局变量last结点,指向当前单链表的最后一个结点,按照前序遍历的次序不断更新last.right就可以得到需要的结果。

public class Solution {    public TreeNode last=null;    public void flatten(TreeNode root) {           if(root==null) return;            last=root;            TreeNode r=root.right;            preOrder(root.left);            preOrder(r);    }     public void preOrder(TreeNode root)    {          if(root==null) return;            TreeNode r=root.right;            last.right=root;            last.left=null;            last=root;            preOrder(root.left);            preOrder(r);    }}

思路二: 观察可以发现,如果当前结点root有左子树,那么当前结点的right指针就指向当前结点的左子树结点,那么当前结点root的右子树往哪里放呢,那就放在它最后应该放在父节点的后面,在前序遍历中,右子树结点的前一个结点就是当前结点root的左子树中最右的一个结点,那么将root的右子树结点连接到root的左子树最右的一个结点即可。遍历的时候如果当前结点有左子树,都要先找到左子树中最右的结点,然后修改指针即可。

public class Solution {    public void flatten(TreeNode root) {     if(root==null) return;     TreeNode rightMost=null;       while(root!=null)     {            TreeNode tempR=root.right;         if(root.left!=null)            {               rightMost=root.left;               while(rightMost.right!=null)                 rightMost=rightMost.right;              root.right=root.left;              root.left=null;              rightMost.right=tempR;            }               root=root.right;     }         }  }
0 0
原创粉丝点击