剑指 Offer 33. 二叉搜索树的后序遍历序列
题目
思路
二叉搜索树定义: 左子树中所有节点的值 << 根节点的值;右子树中所有节点的值 >> 根节点的值;其左、右子树也分别为二叉搜索树。
递归函数:
输入:后序遍历数组,数组首部index,数组尾部index
判断条件:i>=j是返回true以及代码中最终的tmp与j的数值判断
功能:找出root节点,以及左子树和右子树,并对左右子树进行递归,判断左子树必须比root值小,右子树必须比root值大
代码
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder,0,postorder.length-1);
}
public boolean recur(int[] arr,int i,int j){
if(i>=j) return true;
int tmp=i;
while(arr[tmp]<arr[j]) tmp++;
int m=tmp;
while(arr[tmp]>arr[j]) tmp++;
return tmp==j&&recur(arr,i,m-1)&&recur(arr,m,j-1);
}
}
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
return self.recur(postorder,0,len(postorder)-1)
def recur(self,arr,i,j):
if i>=j:return True
tmp=i
while arr[tmp]<arr[j]: tmp+=1
m=tmp
while arr[tmp]>arr[j] :tmp+=1
return tmp==j and self.recur(arr,i,m-1) and self.recur(arr,m,j-1)
剑指 Offer 34. 二叉树中和为某一值的路径
题目
思路
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
LinkedList<List<Integer>> ans=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recur(root,sum);
return ans;
}
public void recur(TreeNode root,int sum){
if(root==null) return;
path.add(root.val);
sum-=root.val;
if(root.left==null&&root.right==null&&sum==0)
// 记录路径时若直接执行 res.append(path) ,则是将 path 对象加入了 res ;
// 后续 path 改变时, res 中的 path 对象也会随之改变
ans.add(new LinkedList(path));
recur(root.left,sum);
recur(root.right,sum);
// 此处的代码含义:可以保证传进这个函数的(public void recur)root节点刚好在path中消失,以供其他节点使用!!!!!!
path.removeLast();
}
}
# 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]]:
ans,path=[],[]
def recur(root,sum):
if not root:return
path.append(root.val)
sum=sum-root.val
if sum==0 and root.left==None and root.right==None:
# tmp=path
ans.append(list(path))
recur(root.left,sum)
recur(root.right,sum)
path.pop()
recur(root,sum)
return ans