• [LeetCode] 114. Flatten Binary Tree to Linked List Java


    题目:

    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
    

    题意及分析:给出一棵树,要求给出这棵树的先序遍历组成的链表,但是还是用树表示。首先找到根节点左子节点的最右子节点,然后将根节点的右子树移到该点的右节点上;再将根节点的左子节点移到根节点的右子节点上,并将根节点左子树重置为null;然后将根节点向右子节点移动一位,递归即可。

    代码:

    /**
     * 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;
            if(root.left!=null){
                TreeNode cur = root.left;
                while(cur.right!=null){
                    cur=cur.right;
                }
                cur.right=root.right;
                root.right=root.left;
                root.left=null;
            }
            flatten(root.right);
        }
    }

     

     

  • 相关阅读:
    PAT 甲级 1128 N Queens Puzzle
    HDU 1995 R-汉诺塔V
    PAT L1-039 古风排版
    PAT L2-028 秀恩爱分得快
    ZOJ 2060 A-Fibonacci Again
    HDU 2079 选课时间
    HDU 1016 Prime Ring Problem
    理论相关概念原理
    单播字符、字符串收发
    OSAL的原理
  • 原文地址:https://www.cnblogs.com/271934Liao/p/7227457.html
Copyright © 2020-2023  润新知