二叉树算法题

  1. 二叉树的前序遍历
/**
 * 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:
  //  vector<int> res;
    vector<int> preorderTraversal(TreeNode* root) {
   /*     if(root != NULL)
       {
             res.push_back(root->val);
             preorderTraversal(root->left);
             preorderTraversal(root->right);
       }
        return res;
    */
    vector<int> res;
    stack<TreeNode*>call;
    if(root != NULL)call.push(root);
     while(!call.empty())
     {
          TreeNode* tmp = call.top();
          call.pop();
          if(tmp != NULL)
          {
            if(tmp->right) call.push(tmp->right);
            if(tmp->left) call.push(tmp->left);
            call.push(tmp);
            call.push(NULL);
          }
          else
          {
              res.push_back(call.top()->val);
              call.pop();
          }

     }
     return res;
    }
};
  1. 二叉树中序遍历
/**
 * 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:
   // vector<int> res;
    vector<int> inorderTraversal(TreeNode* root) {
    /*    if(root != NULL)
        {
              inorderTraversal(root->left);
              res.push_back(root->val);
              inorderTraversal(root->right);
        }
        return res;
        */
        vector<int> res;
        stack<TreeNode*> call;
        if(root != NULL) call.push(root);
        while(!call.empty())
        {
            TreeNode* tmp = call.top();
            call.pop();
            if(tmp != NULL)
            {
                if(tmp->right) call.push(tmp->right);
                call.push(tmp);
                call.push(NULL);
                if(tmp->left) call.push(tmp->left);
            }
            else
            {
                res.push_back(call.top()->val);
                call.pop();
            }
        }
        return res;
    }
};
  1. 二叉树的后序遍历
/**
 * 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:
   // vector<int> res;
    vector<int> postorderTraversal(TreeNode* root) {
    /*    if(root != NULL)
        {
            postorderTraversal(root->left);
            postorderTraversal(root->right);
            res.push_back(root->val);
        }
        return res;
        */
        vector<int> res;
        stack<TreeNode*> call;
        if(root != NULL) call.push(root);
        while(!call.empty())
        {
            TreeNode* tmp = call.top();
            call.pop();
            if(tmp != NULL)
            {
                if(tmp != NULL) call.push(tmp);
                call.push(NULL);
                if(tmp->right) call.push(tmp->right);
                if(tmp->left) call.push(tmp->left);      
            }
            else
            {
                res.push_back(call.top()->val);
                call.pop();
            }
        }
        return res;
    }
};
  1. 二叉树的层序遍历 。
/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
         vector<vector<int>> res;
         if(root == nullptr)
         return res;
         queue<TreeNode*>q;
         q.push(root);
         while(!q.empty())
         {
             vector<int> tmp;
             int size = q.size();
             for(int i = 0;i < size;i++)
             {
                 TreeNode* Ttmp = q.front();
                 q.pop();
                 tmp.push_back(Ttmp->val);
                 if(Ttmp->left) q.push(Ttmp->left);
                 if(Ttmp->right) q.push(Ttmp->right);
             }
             res.push_back(tmp);
         }
         return res;
    }
};
  1. 检查两颗树是否相同。c
/**
 * 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 false;
        if(p != NULL && q == NULL)
            return false;
        if(p == NULL && q==NULL)
            return true;
        if(p->val != q->val)
        return false;
        return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
        
      /*  stack<TreeNode*>S;
        S.push(p);
        S.push(q);
        while(!S.empty())
        {
            TreeNode* q = S.top();
            S.pop();
             TreeNode* p = S.top();
            S.pop();
            if(q==NULL && p==NULL) continue;
            if(q!=NULL && p==NULL) return false;
            if(q==NULL && p!=NULL) return false;
            if(q->val != p->val) return false;
            else
            {
                S.push(p->left);
                S.push(q->left);
                S.push(q->right);
                S.push(p->right);
            }
        }
        return true;
        */
    }
};
  1. 对称二叉树。
/**
 * 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) {
       return isSymmetric(root,root);
    }
    bool isSymmetric(TreeNode* q,TreeNode* p) {
      /* if(root1 != NULL && root2 == NULL)
       return false;
        if(root1 == NULL && root2 != NULL)
       return false;
      if(root1 == NULL && root == NULL)
       return true;
       if(root1->val != root2->val)
       return false;
       return isSymmetric(root1->left,root2->right) &&
               isSymmetric(root1->right,root2->left);
               */
        stack<TreeNode*>S;
        S.push(p);
        S.push(q);
        while(!S.empty())
        {
            TreeNode* q = S.top();
            S.pop();
             TreeNode* p = S.top();
            S.pop();
            if(q==NULL && p==NULL) continue;
            if(q!=NULL && p==NULL) return false;
            if(q==NULL && p!=NULL) return false;
            if(q->val != p->val) return false;
            else
            {
                S.push(p->left);
                S.push(q->right);
                S.push(q->left);
                S.push(p->right);
            }
        }
        return true;
    }
};
  1. 另一颗树的子树。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool dfs(TreeNode* s,TreeNode* t)
    {
        if(s == NULL && t==NULL) return true;
        if(s == NULL || t == NULL) return false;
        if(s->val != t->val) return false;
        return dfs(s->left,t->left) && dfs(s->right,t->right);
    }
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(s == NULL) return false;
        if(dfs(s,t)) return true;
        return isSubtree(s->left,t) || isSubtree(s->right,t);
    }
};
  1. 二叉树最大深度。
/**
 * 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 == NULL) return 0;
        int l = maxDepth(root->left)+1;
        int r = maxDepth(root->right)+1;
        return l>r?l:r;
    }
};

class Solution {
public:
    int maxDepth(TreeNode* root) {
         if(root==NULL) return 0;
         deque<TreeNode*> q;
         q.push_back(root);
         int deep=0;
         while(!q.empty())
         {
             deep++;
             int num=q.size();
             for(int i=1;i<=num;i++)
             {
                TreeNode* p=q.front();
                q.pop_front();
                if(p->left) q.push_back(p->left);
                if(p->right) q.push_back(p->right);
             }
         }
         return deep;         
    }
};

  1. 二叉树的构建及遍历。
#include<iostream>
#include<string>
using namespace std;
string str;
int i;
struct TreeNode
{
    char val;
    struct TreeNode* lchild,*rchild;
    TreeNode(char c) :val(c),lchild(NULL),rchild(NULL){};
};
TreeNode* createTree()
{
    char c = str[i++];
    if(c == '#') return NULL;
    TreeNode *root = new TreeNode(c);
    root->lchild = createTree();
    root->rchild = createTree();
    return root;
}
void inOrderTraversal(TreeNode* root)
{
    if(!root) return;
    inOrderTraversal(root->lchild);
    cout<<root->val<<" ";
    inOrderTraversal(root->rchild);
}

int main()
{
    while(cin>>str)
    {
        i = 0;
        TreeNode *root = createTree();
        inOrderTraversal(root);
        cout<<endl;
    }
    return 0;
}
  1. 二叉树创建字符串。
/**
 * 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:
    void preAccess(TreeNode* t,string& str)
    {
        if(t == NULL) return;
        str += to_string(t->val);
        if(t->left || t->right)
        {
            str += "(";
            preAccess(t->left,str);
            str += ")";
        }
        if(t->right)
        {
            str += "(";
            preAccess(t->right,str);
            str += ")";
        }
    }
    string tree2str(TreeNode* t) {
        string res = "";
        preAccess(t,res);
        return res;
    }
};
  1. 判断一颗二叉树是否是平衡二叉树。
/**
 * 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 isBalanced(TreeNode* root) {
        return box(root) != -1;
    }

    int box(TreeNode* root)
    {
        if(root == NULL) return 0;
        int l = box(root->left);
        if(l == -1) return -1;
        int r = box(root->right);
        if(r == -1) return -1;
        return abs(l-r) < 2 ? max(l,r)+1:-1;

    }
};

c
12. 根据一棵树的前序遍历与中序遍历构造二叉树。

/**
 * 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) {
        int size = inorder.size();
        if(size == 0)
        return NULL;
        TreeNode* root = new TreeNode(preorder[0]);
        vector<int>pre_left,vin_left,pre_right,vin_right;
        int head = 0;
        while(inorder[head] != preorder[0])
           head++;
        for(int i = 0;i < head;i++)
        {
            pre_left.push_back(preorder[i+1]);
            vin_left.push_back(inorder[i]);
        }

        for(int i = head+1;i < size;i++)
        {
            pre_right.push_back(preorder[i]);
            vin_right.push_back(inorder[i]);
        }
        root->left = buildTree(pre_left,vin_left);
        root->right = buildTree(pre_right,vin_right);
        return root;
    }
};
  1. 根据一棵树的中序遍历与后序遍历构造二叉树。
/**
 * 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) {
        int size = postorder.size();
        if(size == 0)
        return NULL;
        int  head = 0;
        TreeNode* root = new TreeNode(postorder[size-1]);
        while(inorder[head] != postorder[size-1])
        head++;
        vector<int> vin_left,post_left,vin_right,post_right;
        for(int i = 0;i < head;i++)
        {
            vin_left.push_back(inorder[i]);
            post_left.push_back(postorder[i]);
        }
        for(int i = head+1;i < size;i++)
        {
            vin_right.push_back(inorder[i]);
            post_right.push_back(postorder[i-1]);
        }
        root->left = buildTree(vin_left,post_left);
        root->right = buildTree(vin_right,post_right);
        return root;
        
    }
};
  1. 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先 。
/**
 * 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* res;
    bool dfs(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if(root == NULL) return false;
        int lson = dfs(root->left,p,q);
        int rson = dfs(root->right,p,q);
        if((lson&&rson) || ((root->val==p->val||root->val == q->val) &&(lson || rson)))
        {
            res = root;
        }
        return lson || rson ||(root->val==p->val||root->val == q->val);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root,p,q);
        return res;
    }
};

二叉树最远节点

int HeightOfBinaryTree(BinaryTreeNode*pNode, int&nMaxDistance){
	if (pNode == NULL)
		return -1;   //空节点的高度为-1
	//递归
	int nHeightOfLeftTree = HeightOfBinaryTree(pNode->m_pLeft, nMaxDistance) + 1;   //左子树的的高度加1
	int nHeightOfRightTree = HeightOfBinaryTree(pNode->m_pRight, nMaxDistance) + 1;   //右子树的高度加1
	int nDistance = nHeightOfLeftTree + nHeightOfRightTree;    //距离等于左子树的高度加上右子树的高度+2
	nMaxDistance = nMaxDistance > nDistance ? nMaxDistance : nDistance;            //得到距离的最大值
	return nHeightOfLeftTree > nHeightOfRightTree ? nHeightOfLeftTree : nHeightOfRightTree;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值