zoukankan      html  css  js  c++  java
  • leetcode 二叉树系列

    1.二叉树转链表

    Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place.

    For example,
    Given

             1
            / \
           2   5
          / \   \
         3   4   6
    

    The flattened tree should look like:

    1
        \
         2
          \
           3
            \
             4
              \
               5
                \
                 6

    class Solution {
    public:
        vector<TreeNode *>v;
        void flatten(TreeNode *root) 
        {
          v.clear();
          if(root==NULL)return;
          PreOrder(root);
          TreeNode *p=root;
          for(int i=1;i<v.size();i++)
          {
              TreeNode *q=v[i];
              p->left=NULL;
              p->right=q;
              p=q;
          }       
        }
        void PreOrder(TreeNode *root)
        {
           if(root)v.push_back(root);
           if(root->left)PreOrder(root->left);
           if(root->right)PreOrder(root->right);
        }
    };
    

     2.数组建立平衡二叉树

    Convert Sorted Array to Binary Search Tree

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

    此方法非常巧妙,取中点作为根节点,递归建立左右子树

        class Solution {
        public:
            TreeNode *sortedArrayToBST(vector<int> &num) {
                return _sortArrayToBST(num, 0, num.size()-1);
            }
        private:
            TreeNode *_sortArrayToBST(vector<int> &num, int i, int j){
                if(i>j){
                    return NULL;
                }
                else{
                    int r = (i+j+1)/2;
                    TreeNode *root = new TreeNode(num[r]);
                    root->left = _sortArrayToBST(num, i, r-1);
                    root->right = _sortArrayToBST(num, r+1, j);
                    return root;
                }       
            }
        }; 
    
  • 相关阅读:
    SQLyog快捷键
    程序员常用工具下载地址及方式
    mysql基础命令
    Excel常用快捷键
    PS快捷键
    MySQL安装及配置
    Excel常用公式
    数据库函数
    mysql update语句的用法
    MySQL使用存储过程批量更新数据库所有表某个字段值
  • 原文地址:https://www.cnblogs.com/tgkx1054/p/3070164.html
Copyright © 2011-2022 走看看