1. 二叉树的前/中/后序遍历
1) Sum Root to Leaf Numbers
在前序遍历过程中,对于当前结点,记录从根结点到当前结点组成的数字。当当前结点为叶节点时,将这个数字加到sum上。
2) Flatten Binary Tree to Linked List
前序遍历,前序序列中的前一个结点作为新的父结点。
3) Path Sum I II
前序遍历,将从根结点到当前结点的和记录下来,当到达叶结点时与sum进行比较。
4) Symmetric Tree
中序序列是回文,说明是对称树。
5) Recover Binary Search Tree
中序遍历。如果出现前面的元素大于后面的情况,即为需要修复的结点。
6) Validate Binary Search Tree
中序遍历。如果出现前面的元素大于等于后面的情况,即不是BST。
2. 二叉树的next指针
1) Populating Next Right Pointers in Each Node I II
将二叉树中同一层的结点用next指针连接起来,最右侧的结点的next指针指向NULL。
如果这是一棵完全二叉树,采用递归或宽度优先搜索的方法。空间代价分别为O(1)和O(n)。
void connect(TreeLinkNode *node, TreeLinkNode *rightBrother)
{
if(node == NULL)
return;
node->next = rightBrother;
connect(node->left, node->right);
if(rightBrother != NULL)
connect(node->right, rightBrother->left);
else
connect(node->right, NULL);
}
如果这是一棵任意的二叉树,采用递归或宽度优先搜索的方法。空间代价分别为O(1)和O(n)。
递归函数的参数为上一层(已经链接好next指针的)的最左边的结点p。
在递归函数中,沿着上一层的next链右移。将本层的next链链接起来,记录本层的最左边结点q,用来递归的对下一层结点完成链接。
void connect(TreeLinkNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL) return;
TreeLinkNode *p = root,*q = NULL,*nextNode = NULL;
//p 是上一层结点,已经next链接完毕;nextNode是当前层结点中最左边的,q遍历当前层的结点。
while(p) {
if(p->left != NULL) {
if(q != NULL) {
q->next = p->left;
}
q = p->left;
if(nextNode == NULL) nextNode = q;
}
if(p->right != NULL) {
if(q!= NULL) {
q->next = p->right;
}
q = p->right;
if(nextNode == NULL) nextNode = q;
}
p = p->next;
}
connect(nextNode);
}
3. 二叉树的递归
1) Minimum/Maximum Depth of Binary Tree
int minDepth(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL)
return 0;
// leaf node, the depth is 1
if(root->left == NULL && root->right == NULL)
return 1;
// if one node has only one child, then its depth is decided by the child
if(root->left == NULL)
return minDepth(root->right)+1;
if(root->right == NULL)
return minDepth(root->left)+1;
// if one node has two children, then its depth is decided by two children
int leftMin = minDepth(root->left);
int rightMin = minDepth(root->right);
return leftMin<rightMin ? leftMin+1 : rightMin+1;
}
2) Balanced Binary Tree
左右子树是否高度差小于等于1,左右子树是否都为平衡二叉树。
bool isBalanced(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL)
return true;
// the depth of left subtree and right subtree differ by no more than 1
int leftHeight = height(root->left);
int rightHeight = height(root->right);
if(abs(leftHeight-rightHeight) > 1)
return false;
// left subtree and right subtree are both balanced
return isBalanced(root->left)&&isBalanced(root->right);
}
对于链表head到tail,找到中间结点mid,以mid为root,以head到preMid作为左子树,以postMid到tail作为右子树。递归的创建BST。
Convert Sorted Array to Binary Search Tree
同理。
4) Construct Binary Tree from Inorder and Preorder/Postorder Traversal
对于序列从left到right,以left/right为根结点,然后将剩下的序列分成两部分,递归的建立左右子树。
5) Same Tree
根结点相同,且递归的判断左右子树都是same tree。