二叉树-总结例题

1-从中序与后序遍历序列构造二叉树

给定二叉树的后序遍历和二叉树的中序遍历

想法:

  1. 先根据后序遍历的最后一个元素构造根节点
  2. 寻找根节点在中序遍历中的位置
  3. 递归构建根节点的左右子树
/**
* 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:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(inorder.size() == 0 || postorder.size() == 0)
return NULL;
int _is = 0;
int _ie = inorder.size()-1;
int _ps = 0;
int _pe = postorder.size()-1;
return build(inorder,postorder,_is,_ie,_ps,_pe); }
// 构建节点的递归函数
TreeNode* build(vector<int>& inorder, vector<int>& postorder,int is,int ie,int ps,int pe)
{
// 构建根节点
TreeNode* ans = new TreeNode(postorder[pe]);
int ll = 0;
int rl = 0;
for(int i = is ; i <= ie ; ++i )
{
if(inorder[i] == postorder[pe])
{
// 左子树长度
ll = i - is;
// 右子树长度
rl = ie - i;
}
}
// 构建左子树
if ( ll > 0 )
{
ans->left = build(inorder,postorder,is,is+ll-1,ps,ps+ll-1);
}
// 构建右子树
if ( rl > 0 )
{
ans->right = build(inorder,postorder,ie-rl+1,ie,pe-rl,pe-1);
}
return ans;
}
};

总结:

  1. 返回类型为pointer,异常情况可以直接返回NULL
  2. 上面的代码里用了两个变量,ll和rl分别表示,左右子树在vector里面的长度。
  3. 每次调用递归函数,都用ll和rl改变两个容器的首尾下标。

2-从前序与中序遍历序列构造二叉树

想法:

  1. 先根据先序遍历的最后一个元素构造根节点
  2. 寻找根节点在中序遍历中的位置
  3. 递归构建根节点的左右子树
/**
* 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:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(inorder,preorder,0,inorder.size()-1,0,preorder.size()-1);
}
TreeNode* build(vector<int>& inorder,vector<int>& preorder, int is,int ie,int ps,int pe)
{
if(inorder.size()==0 || preorder.size()==0)
{
return NULL;
}
int ll = 0 ;
int rl = 0 ;
TreeNode* ans = new TreeNode(preorder[ps]);
for(int i = is; i<= ie; i++)
{
if(preorder[ps]==inorder[i])
{
ll = i - is ;
rl = ie - i;
}
}
if ( ll > 0 )
{
ans->left = build (inorder,preorder,is,is+ll-1,ps+1 ,ps+ll );
}
if ( rl > 0 )
{
ans->right = build(inorder,preorder,ie-rl+1,ie,pe-rl+1,pe);
}
return ans;
}
};

3-填充每个节点的下一个右侧节点指针(完美二叉树)

想法:

  1. 通过层次遍历,使用队列
  2. 每一层的最后一个节点指向next,否则就指向下一个
class Solution {
public:
Node* connect(Node* root) {
if( root == NULL)
return NULL;
queue<Node*> q;
q.push(root);
// 记录每一层的元素个数
while( ! q.empty())
{
int num = q.size();
// 遍历当前层(队列)里面的每个元素
for(int i = 0; i < num; i++)
{
// p指向 是队列的头节点
Node* p = q.front();
// 出队
q.pop();
// 如果到当前层最后一个元素了,next指针指向NULL,队未空,next指向队头节点
if(i == num-1)
p->next = NULL;
else
p->next = q.front();
// p 的左右孩子节点入队
if( p->left != NULL )
q.push( p->left );
if ( p->right != NULL )
q.push( p->right );
}
}
return root;
}
};

4-填充每个节点的下一个右侧节点指针(非完美二叉树)

我的解法同上。

class Solution {
public:
Node* connect(Node* root) {
if( root == NULL)
return NULL;
queue<Node*> q;
q.push(root);
// 记录每一层的元素个数
while( ! q.empty())
{
int num = q.size();
// 遍历当前层(队列)里面的每个元素
for(int i = 0; i < num; i++)
{
// p指向 是队列的头节点
Node* p = q.front();
// 出队
q.pop();
// 如果到当前层最后一个元素了,next指针指向NULL,队未空,next指向队头节点
if(i == num-1)
p->next = NULL;
else
p->next = q.front();
// p 的左右孩子节点入队
if( p->left != NULL )
q.push( p->left );
if ( p->right != NULL )
q.push( p->right );
}
}
return root;
}
};

5-二叉树的最近公共祖先

自己的想法 :

  1. 在树中分别查找目标节点。把查找的路径存放到两个栈里。
  2. 其中一个栈依次出栈,在另个栈里查找这个出栈的节点。
  3. Note:因为搜索到的路径是唯一的。
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
stack<TreeNode*> A;
stack<TreeNode*> B;
find(root,p,A);
find(root,q,B); vector<int> bb;
for(int i = 0; i< B.size();++i)
{
bb.push_back(B.top()->val);
B.pop();
}
while(!A.empty())
{
TreeNode* ans = A.top();
for(int i = 0 ; i< bb.size();++i)
{
if( ans->val == bb[i])
return ans;
}
}
return NULL;
}
void find (TreeNode* root ,TreeNode* target, stack<TreeNode*> &ss)
{
if (! root)
return ;
if(root->val == target->val)
{
ss.push(root);
}
if(root->left != NULL)
{
vector<int> lv = dfs(root->left);
for(int i = 0; i < lv.size() ; ++i )
{
if(lv[i] == target->val)
{
ss.push(root->left);
find(root->left,target ,ss);
}
}
}
if(root->right != NULL)
{
vector<int> rv = dfs(root->right);
for(int i = 0; i < rv.size() ; ++i )
{
if(rv[i] == target->val)
{
ss.push(root->right);
find(root->right,target,ss);
}
}
}
} vector<int> dfs(TreeNode* root)
{
vector<int> order;
helper(root,order);
return order;
}
void helper( TreeNode* root, vector<int>& vv)
{
if(root->left!=NULL)
helper(root->left,vv);
vv.push_back(root->val);
if(root->right != NULL)
helper(root->right,vv);
}
};
代码超出时间限制

看看人家的代码吧:

/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root || !p || !q)
return NULL;
vector<TreeNode*> A;
vector<TreeNode*> B;
dfs(root,p,A);
dfs(root,q,B); TreeNode* ans ;
int len = min(A.size(),B.size());
for(int i = 0; i < len ; i++)
{
if(A[i]->val != B[i]->val)
break;
ans = A[i];
}
return ans; }
bool dfs(TreeNode* root,TreeNode* target,vector<TreeNode*>& path)
{
if( root == target ){
path.push_back(root);
return true;
}
path.push_back(root);
if( root->left && dfs( root->left , target,path ))
return true;
if(root->right && dfs( root->right , target , path ))
return true;
// 回溯???
path.pop_back();
return false;
} };

问题:

  1. 在深度遍历函数里,pop_back()的理解:回溯???
  2. for循环的问题
        for(int i = 0; i < len ; i++)
{
if(A[i]->val != B[i]->val)
break;
ans = A[i];
}

LeetCode---二叉树3-总结例题的更多相关文章

  1. LeetCode二叉树实现

    LeetCode二叉树实现 # 定义二叉树 class TreeNode: def __init__(self, x): self.val = x self.left = None self.righ ...

  2. LeetCode 二叉树,两个子节点的最近的公共父节点

    LeetCode 二叉树,两个子节点的最近的公共父节点 二叉树 Lowest Common Ancestor of a Binary Tree 二叉树的最近公共父亲节点 https://leetcod ...

  3. leetcode二叉树题目总结

    leetcode二叉树题目总结 题目链接:https://leetcode-cn.com/leetbook/detail/data-structure-binary-tree/ 前序遍历(NLR) p ...

  4. [LeetCode] 二叉树相关题目(不完全)

    最近在做LeetCode上面有关二叉树的题目,这篇博客仅用来记录这些题目的代码. 二叉树的题目,一般都是利用递归来解决的,因此这一类题目对理解递归很有帮助. 1.Symmetric Tree(http ...

  5. LeetCode二叉树的前序、中序、后序遍历(递归实现)

    本文用递归算法实现二叉树的前序.中序和后序遍历,提供Java版的基本模板,在模板上稍作修改,即可解决LeetCode144. Binary Tree Preorder Traversal(二叉树前序遍 ...

  6. LeetCode 二叉树的层次遍历

    第102题 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 ...

  7. LeetCode 二叉树的锯齿形层次遍历

    第103题 给定一个二叉树,返回其节点值的锯齿形层次遍历.(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行). 例如: 给定二叉树 [3,9,20,null,null,15,7] ...

  8. Leetcode——二叉树常考算法整理

    二叉树常考算法整理 希望通过写下来自己学习历程的方式帮助自己加深对知识的理解,也帮助其他人更好地学习,少走弯路.也欢迎大家来给我的Github的Leetcode算法项目点star呀~~ 二叉树常考算法 ...

  9. LeetCode 二叉树的最小深度

    计算二叉树的最小深度.最小深度定义为从root到叶子节点的最小路径. public class Solution { public int run(TreeNode root) { if(root = ...

  10. LeetCode - 二叉树的最大深度

    自己解法,欢迎拍砖 给定一个二叉树,找出其最大深度. 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数. 说明: 叶子节点是指没有子节点的节点. 示例:给定二叉树 [3,9,20,null,nu ...

随机推荐

  1. 898A. Rounding#数的舍入

    题目出处:http://codeforces.com/problemset/problem/898/A 题目大意:找一个数最近的整十的数 #include<iostream> using ...

  2. 吴裕雄--天生自然python机器学习:机器学习简介

    除却一些无关紧要的情况,人们很难直接从原始数据本身获得所需信息.例如 ,对于垃圾邮 件的检测,侦测一个单词是否存在并没有太大的作用,然而当某几个特定单词同时出现时,再辅 以考察邮件长度及其他因素,人们 ...

  3. 吴裕雄--天生自然python学习笔记:python 用firebase实现英文电子词典

    Firebase 版电子词典 学英语是许多 人一辈子的麻烦 . 所以本例中,我们开发一个英汉词典,用户执 行程序后,单击“翻译”按钮即可显示该单词的中文翻译 . 英汉词典标准版 因为这个案例的数据必须 ...

  4. overflow text-overflow 超过部分隐藏问题

    overflow:是针对容器内所有的数据溢出的一种统一处理方式,不管容器内的存储的是文本 图片还是其他的数据 统一取值; hidden隐藏, scroll滚动条显示,visible溢出显示text-o ...

  5. vue实现动态绑定class--多个按钮点击一个有一个

    <template> //v-for循环出来多个按钮,便于获取index         <span v-for="(item,index) in list" : ...

  6. Socket设置超时时间

    主要有以下两种方式,我们来看一下方式1: Socket s=new Socket(); s.connect(new InetSocketAddress(host,port),10000); 方式2: ...

  7. sqlserver中的数据导到mysql相关

    一.在sqlserver中生成数据表脚本,粘贴到记事本中,如下语法要进行替换 1.int IDENTITY (1, 1) NOT NULL——>id int unsigned NOT NULL ...

  8. 92)PHP,cookie代码补充

    (1)Cookie值,仅仅支持字符串类型. (2)Cookie键,可以写成下标数组形式. beifen.php <?php /** * @第一个值是name * @第二个值是value * na ...

  9. Qt static关键字全局变量

    创建全局变量.h文件 globalvariable.h #ifndef GLOBALVARIABLE_H #define GLOBALVARIABLE_H #include <QImage> ...

  10. JavaScript学习总结(四)function函数部分

    转自:http://segmentfault.com/a/1190000000660786 概念 函数是由事件驱动的或者当它被调用时执行的可重复使用的代码块. js 支持两种函数:一类是语言内部的函数 ...