深度优先搜索
- 判断一棵树是不是二叉搜索树
注:
- 判断两个二叉树是否相同
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL && q==NULL)
return true;
if(p==NULL || q==NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};
- (LeetCode 101) 判断一棵树是不是镜像二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
return Symmetric(root->left,root->right);
}
private :
bool Symmetric(TreeNode*a, TreeNode *b){
if(!a && !b)
return true;
if(!a|| !b)
return false;
return (a->val==b->val)&&Symmetric(a->left,b->right) && Symmetric(a->right,b->left);
}
};
- (LeetCode 102) 树的层次遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if TreeNode is None:
return []
result = []
que = [root]
que2 = []
tmp = []
while(len(que)>0):
vv= que.pop(0)
if vv== None:
continue
if vv.left!=None:
que2.append(vv.left)
if vv.right!=None:
que2.append(vv.right)
tmp.append(vv.val)
if(len(que)==0):
result.append(tmp)
tmp = []
que = que2.copy()
que2 = []
return result
- (leetcode 104) 二叉树最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
}
};
- (leetcode 105) 从前序与中序遍历构造二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if len(preorder)==0:
return None
root = preorder[0]
indx = inorder.index(root)
root = TreeNode(root)
root.left = self.buildTree(preorder[1:1+indx],inorder[:indx])
root.right = self.buildTree(preorder[1+indx:],inorder[indx+1:])
return root
7.(leetcode 106) 从后序中序建立树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if len(postorder)==0:
return None
root = postorder[-1]
indx = inorder.index(root)
root = TreeNode(root)
root.left=self.buildTree(inorder[:indx],postorder[:indx])
root.right=self.buildTree(inorder[indx+1:],postorder[indx:-1])
return root
- (leetcode 108) 有序数组转为二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if len(nums)==0:
return None
lent = len(nums)
root = TreeNode(nums[int(lent/2)])
root.left = self.sortedArrayToBST(nums[:int(lent/2)])
root.right = self.sortedArrayToBST(nums[int(lent/2)+1:])
return root
- (leetcode 109) 有序链表转为二叉搜索树
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedListToBST(self, head: ListNode) -> TreeNode:
if (head==None):
return None
nums = []
while(head):
nums.append(head.val)
head = head.next
return self.sortedArrayToBST(nums)
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
if len(nums)==0:
return None
lent = len(nums)
root = TreeNode(nums[int(lent/2)])
root.left = self.sortedArrayToBST(nums[:int(lent/2)])
root.right = self.sortedArrayToBST(nums[int(lent/2)+1:])
return root
- (leetcode 110) 判断平衡二叉树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if(root==None):
return True
if (self.calHigh(root.left) - self.calHigh(root.right) >1) or (self.calHigh(root.left) - self.calHigh(root.right) <-1):
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
def calHigh(self,a):
if(a==None):
return 0
return max(self.calHigh(a.left)+1, self.calHigh(a.right)+1)
- (leetcode 111)二叉树的最小深度
注:和最大深度不一样
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if(root==None):
return 0
if(root.left==None) and (root.right==None):
return 1
elif not root.left:
return self.minDepth(root.right) +1
elif not root.right:
return self.minDepth(root.left) +1
else:
return min(self.minDepth(root.left),self.minDepth(root.right)) +1
12.(leetcode 112) 路径总和
注:当树为空且sum为0时,需要特殊考虑
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
if not root.left and sum==root.val and not root.right:
return True
return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)
(leetcode 113)路径总和及路径
注:这题需要好好琢磨一下,思路和上一题类似,但是多了添加满足条件的点。这应该涉及到递归工作的原理,需要看看相关原理。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
if not root:
return []
self.path = []
self.tmp = sum
def calSum(tmp_path,now,root):
if not root:
return False
if not root.left and not root.right and root.val + now== self.tmp:
self.path.append(tmp_path+[root.val])
if root.left:
calSum(tmp_path+[root.val],now+root.val,root.left)
if root.right:
calSum(tmp_path+[root.val],now+root.val,root.right)
calSum([],0,root)
return self.path
(leetcode 114)二叉树展开为链表
注:代码中注释掉的有问题。涉及到深拷贝,浅拷贝?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if not root:
return None
pre = []
def preOrder(root):
if not root:
return
pre.append(root.val)
preOrder(root.left)
preOrder(root.right)
preOrder(root)
copy = root
# copy = TreeNode(pre[0])
for v in pre[1:]:
copy.right = TreeNode(v)
copy.left = None
copy = copy.right
- (lletcode 116)填充下一个右侧节点指针
"""
# Definition for a Node.
class Node:
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: TreeLinkNode
:rtype: nothing
"""
if not root:
return None
cur = root
next = root.left
while cur.left :
cur.left.next = cur.right
if cur.next:
cur.right.next = cur.next.left
cur = cur.next
else:
cur = next
next = cur.left
return root