let 114. Flatten Binary Tree to Linked List

主题思想: 这种方法有两种方法: 1. 按照提示,按前序顺序记录节点,然后重建树。

AC 代码:

/**
 * 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) {

        if(root==null) return ;
        List<TreeNode> ans=new ArrayList<TreeNode> ();
        preOrder(root,ans);

        TreeNode head=null;
        for(TreeNode node : ans){
            if(head==null) head=node;
            else{

                head.right=node;
                head.left=null;
                head=head.right;
            }
        }
        head.left=null;
        head.right=null;
        root=root.right;
    }
    public void  preOrder(TreeNode root,List<TreeNode> ans){

        if(root==null) return ;
        ans.add(root);
        preOrder(root.left,ans);
        preOrder(root.right,ans);
    }
}
  1. 递归方法。

这应该是处理树的典型方法了,各种递归。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private TreeNode prev=null;
    public void flatten(TreeNode root) {

      if(root==null) return ;
        flatten(root.right);
        flatten(root.left);

        root.right=prev;
        root.left=null;
        prev=root;
    }

}

猜你喜欢

转载自blog.csdn.net/the_conquer_zzy/article/details/79207596