divide&conquer 解决二叉树专项 + 递归

二叉树:递归

  • 平衡二叉树 (左右subtree的height的gap要<=1)
  • BST (Binary Search Tree) in-order 左 根 右的时候为一个ascending的数组。
  • 满二叉树 FullBinaryTree : either 0 nodes or 2 nodes
  • perfect binary
  • complete binary tree 完全二叉树: from left to right fill every node ,you can have a line divided tree into 2 part;left nodes are full ,right nodes are zero。
  • degenerate tree: Degenerate Binary Tree is a Binary Tree where every parent node has only one child node

我感觉这里的divide and conquer 都是使用的调用自己的函数
也就是recursion
比较复杂的理解
当 return 的时候:是给上一个invoked function的result assigned.
虽然是调用的同一块函数 但是每次都是不同的内存地址: 这个讲的很清楚
计算现在的年龄。
image


关于二叉树的题:

二叉树上求值(max/min/average/sum)

596 · Minimum Subtree

问题的本质是不停的求每一个子树的和

左子树的和 + 右子树的和 + 根结点 < 当前的最小值比较

Description
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Example
Example 1:

Input:{1,#,2},2
Output:2
Explanation:
1

2
The second smallest element is 2.
Example 2:

Input:{2,1,3},1
Output:1
Explanation:
2
/
1 3
The first smallest element is 1.


``

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
	/**
	 * @param root: the given BST
	 * @param k: the given k
	 * @return: the kth smallest element in BST
	 */
	// global variable 
	public ArrayList<TreeNode> sort ;

	public int kthSmallest(TreeNode root, int k) {
		// write your code here
		sort = new ArrayList<TreeNode>();
		inorder(root);
		return sort.get(k-1).val;
	}
	//in-order 
	public void inorder(TreeNode root){
		if(root == null){
			return ;
		}   
		inorder(root.left);
		sort.add(root); 
		inorder(root.right);

	}
}

``

考察形态二:二叉树结构变化

453 Flatten Binary Tree to Linked List 将二叉树拆成链表


respectively flatten left and right subtree ,then return the last of each subtree element.

Description
Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the right pointer in TreeNode as the next pointer in ListNode.

Contact me on wechat to get Amazon、Google requent Interview questions . (wechat id : jiuzhang0607)


Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

Example
Example 1:

Input:{1,2,5,3,4,#,6}
Output:{1,#,2,#,3,#,4,#,5,#,6}
Explanation:
	 1
	/ \
   2   5
  / \   \
 3   4   6

1
\
 2
  \
   3
	\
	 4
	  \
	   5
		\
		 6
Example 2:

Input:{1}
Output:{1}
Explanation:
		 1
		 1
Challenge
Do it in-place without any extra memory.

``

	/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
	/**
	 * @param root: a TreeNode, the root of the binary tree
	 * @return: nothing
	 */
	public void flatten(TreeNode root) {
		// write your code here
		flattenAndReturnLastNode(root);

	}
	public TreeNode flattenAndReturnLastNode(TreeNode root){
		if(root == null){
			return null;
		}
		TreeNode lastLeftRoot = flattenAndReturnLastNode(root.left);
		TreeNode lastRightRoot = flattenAndReturnLastNode(root.right);
		if(lastLeftRoot!=null){
			lastLeftRoot.right = root.right;
			root.right = root.left;
			root.left = null;
		}
		if  (lastRightRoot!=null) {
			return lastRightRoot;
		}else if (lastLeftRoot != null){
			return lastLeftRoot;
		}
		return root;


	}

}

``

lowest common ancestor.


最近公共祖先,给两个点。讨论这两个点的位置关系
1.如果两个点在一个子树上一个点是根结点,那么直接返回根结点。也就是说,自己可以是自己的ancestor。
2.如果两个结点分别在根的left subtree一个,right subtree 一个 image

--

Description
Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.

The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.

Contact me on wechat to get Amazon、Google requent Interview questions . (wechat id : jiuzhang0607)

Assuming that both nodes given are present in the tree.

Example
Example 1:

Input:

tree = {1}
A = 1
B = 1
Output:

1
Explanation:

For the following binary tree(only one node):
1
LCA(1,1) = 1
Example 2:

Input:

tree = {4,3,7,#,#,5,6}
A = 3
B = 5
Output:

4
Explanation:

For the following binary tree:

 4
/ \

3 7
/
5 6

LCA(3, 5) = 4


``

	/**
	 * Definition of TreeNode:
	 * public class TreeNode {
	 *     public int val;
	 *     public TreeNode left, right;
	 *     public TreeNode(int val) {
	 *         this.val = val;
	 *         this.left = this.right = null;
	 *     }
	 * }
	 */


	public class Solution {
		/*
		 * @param root: The root of the binary tree.
		 * @param A: A TreeNode in a Binary.
		 * @param B: A TreeNode in a Binary.
		 * @return: Return the least common ancestor(LCA) of the two nodes.
		 */
		public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
			// write your code here
			//recursion exit
			if(root == null){
				return null;
			}
			if(root == A || root == B){
				return root;
			}
			TreeNode left = lowestCommonAncestor(root.left,A,B);
			TreeNode right = lowestCommonAncestor(root.right,A,B);
			if(left!=null && right!=null){
				return root;
			}
			else if(left!=null){
				return left;
			}
			else if(right!=null){
				return right;

			}
			return null;

		}



	}

``

第三类问题:bst 二叉查找树

具有左小右大的特性 所以通常都是用来求解upperbound 和lowerbound 用来逼近
比如这个题目:

Closest Binary Search Tree Value 二叉搜索树中最接近的值

Description
Given a non-empty binary search tree and a target value, find the value in the BST that is closest to the target.

Contact me on wechat to get Amazon、Google requent Interview questions . (wechat id : jiuzhang0607)

Given target value is a floating point.
You are guaranteed to have only one unique value in the BST that is closest to the target.
Example
Example1

Input: root = {5,4,9,2,#,8,10} and target = 6.124780
Output: 5
Explanation:
Binary tree {5,4,9,2,#,8,10}, denote the following structure:
5
/
4 9
/ /
2 8 10
Example2

Input: root = {3,2,4,1} and target = 4.142857
Output: 4
Explanation:
Binary tree {3,2,4,1}, denote the following structure:
3
/
2 4
/
1


``

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
	/**
	 * @param root: the given BST
	 * @param target: the given target
	 * @return: the value in the BST that is closest to the target
	 */
	public int closestValue(TreeNode root, double target) {
		// write your code here
		//coner case
		if (root == null){
			return -1;
		}
		TreeNode lowerBound = findLowerBound(root,target);
		TreeNode upperBound = findUpperBound(root,target);
		if(lowerBound != null && upperBound != null){
			return target-lowerBound.val < upperBound.val-target? lowerBound.val : upperBound.val;
		}
		else if(lowerBound!= null){
			return lowerBound.val;
		}
		return upperBound.val;
	}
	private  TreeNode findLowerBound(TreeNode root,double target){
		if (root == null){
			return null;
		}
		// return need 如果 不返回 就是一次的调用。 返回是要得到一个值
		if (root.val > target){
			return findLowerBound(root.left, target);
		}
		TreeNode lowerBound = findLowerBound(root.right , target);
		return lowerBound!=null ? lowerBound : root;
	}
	 private  TreeNode findUpperBound(TreeNode root,double target){
		if (root == null){
			return null;
		}
		// return need 如果 不返回 就是一次的调用。 返回是要得到一个值
		if (root.val <= target){
			return findUpperBound(root.right, target);
		}
		TreeNode upperBound = findUpperBound(root.left , target);
		return upperBound!=null ? upperBound : root;
	}
}

``

posted @ 2022-06-30 19:16  奋斗中的菲比  阅读(20)  评论(0编辑  收藏  举报