The first 26 questions to prove safety offer--: binary search trees and doubly-linked list

  • Problem-solving ideas:
  • 1. The left subtree of a double chain structure, and returns the list head node.
  • 2. Navigate to the left subtree doubly linked list last node.
  • 3. If the left subtree list is not empty, it will be appended to the current root left subtree list.
  • 4. The dual configuration list right subtree, and returns a list head node.
  • 5. If the right subtree after the list is not empty, the list is added to the root node.
  • 6. Determine whether the node returned by the left subtree list is empty.
public class o_26 {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null)
            return null;
        if (pRootOfTree.left == null && pRootOfTree.right == null)
            return pRootOfTree;

        // 1.将左子树构造成双链表,并返回链表头节点
        TreeNode left = Convert(pRootOfTree.left);
        TreeNode p = left; //p为头结点

        // 2.定位至左子树双链表最后一个节点
        while (p != null && p.right != null)
            p = p.right;

        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if (left != null) {
            p.right = pRootOfTree;
            pRootOfTree.left = p;
        }

        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = Convert(pRootOfTree.right);

        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if (right != null) {
            right.left = pRootOfTree;
            pRootOfTree.right = right;
        }

        return left != null ? left : pRootOfTree;
    }
}

Guess you like

Origin blog.csdn.net/dl674756321/article/details/90550312
Recommended