Egs

remove all values 0 nodes subtree

[return type] : am I a root of 0 subtrees?

改变了tree structure 然后返回root node.

at each root:

1. if left is null, right is null (which means both are 0 nodes subtree).
2. return null if current node is 0. else return cur node.
  public void delele (TreeNode root) {
      deleteHelper(root);
  }
  private TreeNode deleteHelper(TreeNode root) {
      if (root == null) {
            return root;
      }
      TreeNode left = deleteHelper(root.left);
      TreeNode right = deleteHelper(root.right);
      if (root.val == 0 && left == null && right == null) {
            return null;
      }
      return root;
  }

Retain only range of range [min,max] of given BST.

This is not bst inorder traversal.

-> BST link to Array

-> if you want to change sturcture of a tree, you have to return a ptr

[return] tree rooted at root (all nodes are among min,max).

    TreeNode retainRange(TreeNode root, int min, int max) {
        if (root == null) {
            return root;
        }
        if (root.val > max) { 
             root.left = retainRange(root.left);
             return root.left;
        } else if (root.val < min) {
            root.right = retain(root.right);
            return root.right;
        } else {
            root.left = retainRange(root.left);       
            root.right = retain(root.right);
            return root;
        }
    }
  //refactor
       TreeNode retainRange(TreeNode root, int min, int max) {
            if (root == null) {
                return root;
            }
            root.left = retainRange(root.left);
            root.right = retainRange(root.right);
            if (root.val > max || root.val < min) {
                return root.left == null ? root.right : root.left;
            }
            return root;
        }

Heapify a Tree.

Heap Property: ...

left < root && right < root.

    TreeNode heapify(TreeNode root) {
        if (root == null) {
            return root;
        }
        root.left = heapify(root.left);
        root.right = heapify(root.right);
        return percolateDown(root);
    }

Border View

leftMost path + rightMost path + leaf path

leftMost Path : left child of root on leftMost path. rightMost path: right child of root on rightMost path. leaf path : left == null && right == null

Requirement : 先打印left,再打印leaf,再打印right.

List<Integer> res = new ArrayList<>();
public void borderView(TreeNode root, boolean onLeft, boolean onRight) {
    if (root == null) {
        return;
    }
    if (onLeft || root.left == null && root.right == null) {
        res.add(root.val);
    }
    borderView(root.left, true, false);
    borderView(root.right,false,true);
    //exclude root val && leaf val
    if (onRight && !onLeft && !(root.left == null && root.right == null)) {
        res.add(root.val);
    }
}

results matching ""

    No results matching ""