Leetcode之二叉树展开为链表(深搜)

问题描述

给定一个二叉树,原地将它展开为一个单链表。

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        def(root);
    }
   TreeNode def(TreeNode root) {
    	if(root==null)
    		return null;
    	if(root.left==null) {
    		if(root.right==null)
    			return root;
    		else
    			return def(root.right);
    	}
    	if(root.left.left==null&&root.left.right==null) {
    		if(root.right==null)
    			{
    			root.right=root.left;
    			root.left=null;
    			return root.right;
    			}
    		root.left.right=root.right;
    		root.right=root.left;
    		root.left=null;
    		return def(root.right.right);
    	}
    	TreeNode left=def(root.left);
    	TreeNode right=def(root.right);
    	left.right=root.right;
    	root.right=root.left;
    	root.left=null;
    	if(right==null)
    		return left;
    	return right;
    }
}

posted @ 2021-01-19 16:46  小帆敲代码  阅读(56)  评论(0编辑  收藏  举报