美文网首页
114. Flatten Binary Tree to Link

114. Flatten Binary Tree to Link

作者: namelessEcho | 来源:发表于2017-10-02 00:02 被阅读0次

后序遍历,递归,注意左半部分要跳到尾部才能链接右半 不然会丢失。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
         flatHelper(root);
    }
    private TreeNode flatHelper(TreeNode root)
    {
        if(root==null)return null;
       TreeNode leftPointer = flatHelper(root.left);
       TreeNode rightPointer = flatHelper(root.right);
        root.left=null;
        if(leftPointer!=null)
        {
            root.right=leftPointer;
            while(leftPointer.right!=null)
            {
                leftPointer=leftPointer.right;
            }
           leftPointer.left=null;
           leftPointer.right=rightPointer;
        }
        else
        {
           root.right=rightPointer;
        }
        if(rightPointer!=null)
        {
            rightPointer.left=null;

        }
        return root ;
        
       
    }
}

相关文章

网友评论

      本文标题:114. Flatten Binary Tree to Link

      本文链接:https://www.haomeiwen.com/subject/ivhzextx.html