查找从根到x的最长路径:
遍历,保存沿途结点,即得到从根到当前访问结点的一条路径。
递归深度对应当前访问的结点的层数,亦对应当前得到的路径的长度。
void find_path(node* t,int dep,int &max,int path[],int maxpath[]){
if(t==NULL ) return ;
path[dep]=t->val;
if(t->left==NULL&& t->right==NULL){
if(dep>max) {
max=dep;
for(int i=0;i<=dep;i++){
maxpath[i]=path[i];
}
}
}
find_path(t->left, dep+1, max, path, maxpath);
find_path(t->right, dep+1, max, path, maxpath);
return ;
}
判断从根节点到叶结点的路径和为sum的路径是否存在
//方法一:递归前序遍历
public boolean hasPathSum (TreeNode root, int sum) {
//路径不存在,出口!
if(root==null) return false;
//处理当前节点!
sum-=root.val;//更新值!
if(sum==0&&root.left==null&&root.right==null)
return true;
//遍历左右子树
return hasPathSum(root.left,sum)||hasPathSum(root.right,sum);
}
//非递归
public boolean hasPathSum (TreeNode root, int sum) {
// write code here
//利用两个栈,一个栈存当前路径和,一个用于深度优先遍历!
if(root==null) return false;
Stack<TreeNode> stack1 = new Stack<>();
stack1.add(root);
Stack<Integer> stack2 = new Stack<>();
stack2.add(root.val);
while(!stack1.isEmpty()){
TreeNode cur = stack1.pop();
int curVal = stack2.pop();
if(sum==curVal&&cur.left==null&&cur.right==null){
return true;
}
if(cur.left!=null){
//将左节点和对应的路径和入栈!
stack1.push(cur.left);
stack2.push(curVal+cur.left.val);
}
if(cur.right!=null){
//将右节点和对应的路径和入栈!
stack1.push(cur.right);
stack2.push(curVal+cur.right.val);
}
}
return false;
}
统计一棵二叉树中每层叶结点的数目。
➢层次遍历,需要识别每层的结束(每层结束后,输出该层信息)。
➢可以设置一个不同于队列中其他结点的特殊结点(比如空结点NULL)来表示每层的结束。
➢遍历第一层时,先将根结点入队,再将NULL入队。在遍历过程中,当NULL出队时,表示已经遍历完一层,将NULL再入队,此时NULL即为下一层的结尾
void LeafInEachLevel(node* root){
if(root==NULL) return;
queue<node*> q;
int level=0;//层数
int cnt=0;//叶结点个数
q.push(root);
q.push(NULL);
while(! q.empty()){
node* p=q.front();
q.pop();
if(p==NULL){
printf("第%d层包含%d个叶结点。\n",level,cnt);
level++;
cnt=0;
}
else{
if(p->left==NULL&&p->right==NULL) cnt++;
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
}
}
查找从根结点到某点的路径
void get_Path(node* root,int aim,vector<int>& v,bool& flag){
if(root==NULL||flag==true) return ;
get_Path(root->left,aim,v,flag);
get_Path(root->right,aim,v,flag);
if(root->val==aim||flag==true){
v.push_back(root->val);
if(!flag) flag=true;
}
}
如果需要查找两点间路径,只需找到两点到根结点的路径,然后求最近公共祖先。
查找最短的固定路径和sum
vector<int> FindPath(node* root,int expectNumber,int& min, vector<int>& result,vector<int>& tmp ) {
if(root ==NULL) return result ;
tmp.push_back(root->val);
int k= expectNumber;
int m=tmp.size()-1;
for(int i=m;i>=0;i--) {
k-=tmp[i];
int len=m-i+1;
if(k==0&& len<=min ){
result.assign(tmp.begin()+i, tmp.end());
min=len;
break;
}
if(len>min) break;
}
FindPath(root->left, expectNumber, min, result,tmp);
FindPath(root->right, expectNumber, min, result,tmp);
tmp.pop_back();
return result ;
}