程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> 114. Flatten Binary Tree to Linked List,flattenlinked

114. Flatten Binary Tree to Linked List,flattenlinked

編輯:JAVA綜合教程

114. Flatten Binary Tree to Linked List,flattenlinked


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
代碼如下:
 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public void flatten(TreeNode root) {
12         TreeNode p=root;
13         List<TreeNode> list=PreOrder(root);
14  
15        for(int i=1;i<list.size();i++)
16        {
17            p.right=list.get(i);
18            p.left=null;
19            p=p.right;
20        }
21         
22     }
23     public List<TreeNode> PreOrder(TreeNode root){//樹的前序遍歷
24          List<TreeNode> list=new ArrayList<>();
25          try{
26          list.add(root);
27          
28          if(root.left!=null)
29          list.addAll(PreOrder(root.left));
30          if(root.right!=null)
31          list.addAll(PreOrder(root.right));
32          }catch(NullPointerException e){}
33          return list;
34     }
35 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved