zoukankan      html  css  js  c++  java
  • LeetCode 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 binary tree
     * 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;
                }
                if (root.left==null) {
                    flatten(root.right);
                    return;
                }
    
                TreeNode lefTreeNode=root.left;
    
                TreeNode righTreeNode=root.right;
                if (righTreeNode==null) {
                    flatten(lefTreeNode);
                    root.left=null;
                    root.right=lefTreeNode;
                    return;
                }
                if (lefTreeNode.left==null && 
                        lefTreeNode.right==null&& 
                        righTreeNode.right==null && 
                        righTreeNode.left==null) {
                    root.left=null;
                    root.right=lefTreeNode;
                    lefTreeNode.right=righTreeNode;
                    return;
                    
                }
                
                flatten(lefTreeNode);
                flatten(righTreeNode);
                root.left=null;
                root.right=lefTreeNode;
                lefTreeNode.left=null;
                TreeNode node=lefTreeNode;
                while (node.right!=null) {
                    node=node.right;
                }
                node.right=righTreeNode;
                return;
                
            
        }
    }
  • 相关阅读:
    C# 委托应用总结
    C语言指针总结
    SQL2005四个排名函数(row_number、rank、dense_rank和ntile)的比较
    C#接口
    C# Linq
    C#反射
    重写与重载
    mysql01
    ajax
    bootstrap02导航菜单
  • 原文地址:https://www.cnblogs.com/birdhack/p/4064010.html
Copyright © 2011-2022 走看看