LeetCode刷题记录Java算法提高之LeetCode刷题

LeetCode 897. 递增顺序查找树

2019-08-20  本文已影响0人  TheKey_

897. 递增顺序查找树

给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。

例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]

示例1:
输入:[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  
说明:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-order-search-tree/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

类似问题(中序遍历)LeetCode 94. 二叉树的中序遍历 - 简书

思路:使用栈进行中序遍历

public TreeNode increasingBST(TreeNode root) {
        TreeNode dummyNode = new TreeNode(0);
        TreeNode p = dummyNode;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            p.right = cur;
            p.left = null;
            p = cur;
            cur = cur.right;
        }
        return p.right;
    }

思路:

  1. 创建一个虚拟根节点 dummyNode;
  2. 递归进行中序遍历,先遍历左子树,将当前根节点拼接到 cur.right, 并将当前根节点的左子树置空,在遍历右子树
    private TreeNode cur;
    public TreeNode increasingBST(TreeNode root) {
        TreeNode dummyNode = new TreeNode(0);
        cur = dummyNode;
        helper(root);
        return dummyNode.right;
    }

    private void helper(TreeNode node) {
        if (node == null) return;
        helper(node.left);
        node.left = null;
        cur.right = node;
        cur = node;
        helper(node.right);
    }

复杂度分析:


上一篇下一篇

猜你喜欢

热点阅读