zl程序教程

您现在的位置是:首页 >  其他

当前栏目

leetcode 114.Flatten Binary Tree to Linked List (将二叉树转换链表) 解题思路和方法

2023-09-11 14:14:09 时间

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

思路:这题主要是就是前序遍历。主要解法就是将左子树转换为右支树,同一时候加入在右子树前。左子树求解时,须要主要左子树的深度。

详细代码例如以下:

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

    	TreeNode r = new TreeNode(0);
        fun(root,r);
        root = r.right;
    }
    
    private boolean fun(TreeNode root, TreeNode t){
    	if(root == null){
    		return false;
    	}
    	TreeNode p = root.left;
    	TreeNode q = root.right;
    	
    	t.right = root;
    	t.left = null;
    	
    	if(p != null){
    		if(fun(p, t.right)){
    			if(q != null){
    				TreeNode k = t.right;
    				while(k.right != null){
    					k = k.right;
    				}
    				fun(q,k);
    			}
    		}else{
    			if(q != null){
    				fun(q,t.right);
    			}
    		}
    	}else{
    		if(q != null){
				fun(q,t.right);
			}
    	}
    	return true;
    }
}