第8章:LeetCode--算法:二叉树的创建、遍历、删除、求高度

创建> 需要给定一个root的key,所有小于这个key的放到左边,大于key的放到右边, 比如vector<int> tree = {5,2,7,1,9,3,8},最后的树:

           5
          / \
         2   7
        /\   /\
       1  3  8 9

实现:

TreeNode* AddNode(int key, int direction, TreeNode* root)
 {
     if(direction == 0)//左孩子
     {
         if(root->leftChild == NULL){//找到对应的叶节点插入
             root->leftChild = new binaryTreeNode<T>(key);
         }
         else{
             root->leftChild = AddNode(key, direction, root->leftChild);
         }
     }
     else//右孩子
     {
         if (root->rightChild == NULL) {//找到相应的叶节点插入
             root->rightChild = new binaryTreeNode<T>(key);
         }
         else{
             root->rightChild = AddNode(key, direction, root->rightChild);
         }
     }
     
     return root;
}
//vector[0]作为root
TreeNode* createTree(vector<int>& tree){
      int nodes = tree.length();
      int pos = 0;
      if(nodes<1) return NULL;
      TreeNode* root = new TreeNode(tree[pos++]);

      while(pos < nodes){
            if(tree[pos]<tree[0])
                  root->left = AddNode(tree[pos++], 0, root);
            else
                  root->right = AddNode(tree[pos++], 1, root);
      }
      return root;
}

 

124. Binary Tree Maximum Path Sum  

Input: [-10,9,20,null,null,15,7]   Input: [1,2,3]
 
   -10                                  1
   / \                                 / \
  9  20                               2   3
    /  \
   15   7
 
Output: 42                         Output: 6

/**
 * 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 {
private:
    int dfs(TreeNode* root, int& maxsum) {
        if(!root) return 0;
        int l = max(0,dfs(root->left,maxsum));
        int r = max(0,dfs(root->right,maxsum));
        maxsum = max(l+r+root->val, maxsum);
        return root->val + max(l,r);
    }
public:
    int maxPathSum(TreeNode* root) {
        int maxsum = INT_MIN;
        dfs(root,maxsum);
        return maxsum;
    }
};

  

  

posted on 2019-07-30 21:00  Felizño  阅读(189)  评论(0)    收藏  举报

导航