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


    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;
        }
    }



  • 相关阅读:
    Google Protocol Buffer
    你不知道的JSON的高效率用法
    ContentProvider深度探索
    Messenger实现Android IPC
    AIDL实现Android IPC
    多点触控
    Service通信详解
    并行执行的Service,以媒体转码成新格式为例
    相对完美的后台Service实现播放音乐功能
    用Dalvik指令集写个java类
  • 原文地址:https://www.cnblogs.com/cxchanpin/p/7115648.html
Copyright © 2020-2023  润新知