Leetcode897 遞增順序查找樹[Easy] -JAVA

題目傳送門

Leetcode897 遞增順序查找樹[Easy] -JAVA

題目

給你一個樹,請你 按中序遍歷 重新排列樹,使樹中最左邊的結點現在是樹的根,並且每個結點沒有左子結點,只有一個右子結點。

示例 :

輸入:[5,3,6,2,4,null,8,1,null,null,null,7,9]

       5
      / \
    3    6
   / \    \
  2   4    8
 /        / \ 
1        7   9

輸出:[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 1
  \
   2
    \
     3
      \
       4
        \
         5
          \
           6
            \
             7
              \
               8
                \
                 9  

提示:

給定樹中的結點數介於 1 和 100 之間。
每個結點都有一個從 0 到 1000 範圍內的唯一整數值。

思路

題意就是用中序遍歷實現,將左邊的節點全部移到右邊。
中序遍歷:左-中-右
想到了用DFS(深度優先搜索),一個遞歸的過程。
請看代碼註釋吧!

ps:
哨兵:用於解決邊界問題,在一些鏈表題目裏經常遇到。
具體可以看下:鏈表中的哨兵是怎麼一個作用?

解法

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

    TreeNode pre;
    public TreeNode increasingBST(TreeNode root) {
        if(root == null) return null;

        TreeNode dummy = new TreeNode(0); //小哨兵
        pre = dummy;
        inOrder(root);
        return dummy.right; //所有的節點都會被放到右子樹來
    }

    public void inOrder (TreeNode node){
        if(node == null) return;

        inOrder(node.left); //先將左邊遞歸到底,把所有的左節點會依次拼接到node 上
        node.left=null;      //} 因爲結果是所有的節點移到右節點上,所以左節點刪除
        pre.right = node;        //}  這三行代碼爲具體邏輯
        pre = node;		         //}
        inOrder(node.right); // 剩下的所有的右節點都會放在最後啦。
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章