[Algorithmic topics] Binary Tree

Source: Internet
Author: User
Tags lintcode

1 Same Tree

https://leetcode.com/problems/same-tree/

Given binary trees, write a function to check if they is equal or not.

The binary trees is considered equal if they is structurally identical and the nodes has the same value.

Divide and conquer the idea, if root is equal, then see whether the left and right sub-trees are equal.

/** * 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) {            RE Turn true;        }                if (p = = NULL | | q = = NULL) {            return false;        }                if (p->val! = q->val) {            return false;        }                Return Issametree (P->left, Q->left) && issametree (P->right, q->right);    }};
2 subtree

http://www.lintcode.com/en/problem/subtree/

You have both every large binary trees: T1 , with millions of nodes, and T2 , with hundreds of nodes. Create an algorithm to decide if is T2 a subtree of T1 .

Example

T2 is a subtree of T1 in the following case:

       1                3      / \              / T1 = 2   3      T2 =  4        /       4

T2 isn ' t a subtree of T1 in the following case:

       1               3      / \               T1 = 2   3       T2 =    4        /       4
仍然是分治的思想。如果T1当前root节点与T2的root节点相同,我们才有兴趣判断T2是否是T1的子树。如果不同,判断T2是否是T1的左子树的子树或者是T1的右子树的子树。
/** * Definition of TreeNode: * Class TreeNode {* Public: * int val; * TreeNode *left, *right; * TreeNode (int val) {* This->val = val; * This->left = This->right = NULL; *} *} */class Solution {Publi     C:/** * @param T1, t2:the roots of binary tree.     * @return: True If T2 is a subtree of T1, or false.        */bool Issubtree (TreeNode *t1, TreeNode *t2) {if (T2 = = NULL) {return true;        }////we have exhauste the root1 already if (T1 = = NULL) {return false;            } if (T1->val = = T2->val) {if (Issametree (T1, T2)) {return true; }} return Issubtree (T1->left, T2) | |    Issubtree (T1->right, T2); }private:bool Issametree (TreeNode *t1, TreeNode *t2) {if (T1 = = NULL && T2 = = null) {retur        n true; } if (T1 = = NULL | | T2 = = NULL) {REturn false;        } if (T1->val! = T2->val) {return false;    } return Issametree (T1->left, T2->left) && issametree (T1->right, t2->right); }};
3 depth of the calculation tree
int treedepth (TreeNode *root) {    //base case    if (root = NULL) {        return 0;    }             Return Max (Treedepth (Root->left), treedepth (root->right)) + 1;}
4 Path Sum

https://leetcode.com/problems/path-sum/

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this adding up all the values along the Path equals the given sum.

For example:
Given the below binary tree sum = 22 and,

              5             /             4   8           /   /           /  4         /  \              7    2      1

Return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

/** * 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 Haspathsum (treenode* root, int sum) {        //base case        if (root = NULL) {            Retu RN false;        }                Does the current recursive layer satisfy the criteria?        if (root->val = = Sum && Root->left = = NULL && Root->right = null) {            return true;
   
    }                return Haspathsum (Root->left, sum-root->val) | | haspathsum (root->right, sum-root->val);}    };
   
5 Path Sum II

https://leetcode.com/problems/path-sum-ii/

Given a binary tree and a sum, find all root-to-leaf paths where each path ' s sum equals the Given sum.

For example:
Given the below binary tree sum = 22 and,

              5             /             4   8           /   /           /  4         /  \    /         7 2 5   1

Return

[   [5,4,11,2],   [5,8,4,5]]
Solution 1:
The sum parameter in DFS records the conditions that the current recursive layer needs to meet
/** * 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>> pathsum (treenode* root, int sum) {vector<vector&lt        ;int>> result;        Vector<int> path;        DFS (root, result, path, sum);    return result; } private:void Dfs (TreeNode *root, vector<vector<int>> &result, vector<int> &path, int su        m) {if (root = NULL) {return;                } path.push_back (Root->val); if (root->val = = Sum && Root->left = = NULL && Root->right = = null) {Result.push_back (        path);        } dfs (Root->left, result, path, sum-root->val);                DFS (root->right, result, path, sum-root->val);    Path.pop_back (); }};

Solution 2:

Consider a few questions, who is the Dfs object? When does the push to result condition be satisfied? What is a recursive base?

/** * 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>> pathsum (treenode* root, int sum) {vector<vector&lt        ;int>> result;        Vector<int> path;        DFS (root, result, path, sum);    return result; } private:void Dfs (TreeNode *root, vector<vector<int>> &result, vector<int> &path, const        int &sum) {if (root = NULL) {return;                } path.push_back (Root->val);                        if (Root->left = = NULL && Root->right = = null) {int TMP = 0;            for (Vector<int>::const_iterator ITR = Path.cbegin (); ITR! = Path.cend (); itr++) {tmp + = *itr; } if (tmp = = sum) {Result.push_back(path);        }} dfs (root->left, result, path, sum);        DFS (root->right, result, path, sum);    Path.pop_back (); }};
6 Binary Tree Maximum Path Sum

https://leetcode.com/problems/binary-tree-maximum-path-sum/

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1      /      2   3

Return 6 .

The method of division and treatment is adopted. Requires the maximum path of the current tree and, consider the maximum path of the left subtree and the maximum path to the right subtree, and the maximum path containing the current node and the maximum of the three.

Requirements include the maximum path of the current node, and need to know the single maximum path of the Zuozi and Leftchildsinglemaxsum, the single maximum path of the right subtree, and the rightchildsinglemaxsum. Among them, Max (leftchildsinglemaxsum + rightchildsinglemaxsum + root->val, Leftchildsinglemaxsum + root->val, Rightchildsinglemaxsum + root->val), which is the maximum path that contains the current node and.

From the above analysis, it is not difficult to know that when traversing each node, it is necessary to get its single maximum path and the maximum path and two paths. We encapsulate it as returntype.

/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */struct returntype {returntype (int singlepath, int doublepath): Singlepath_ (Singlepath), Doublepath_ (doublePa    th) {} int singlepath_; int doublepath_;};    Class Solution {Public:int maxpathsum (treenode* root) {return maxpathsumhelper (root). Doublepath_; } private:returntype Maxpathsumhelper (TreeNode *root) {if (root = NULL) {return returntype (0,        Numeric_limits<int>::min ());        }//Devide returntype left = Maxpathsumhelper (Root->left);                ReturnType right = Maxpathsumhelper (root->right); Conquer int singlepath = Getmax (Left.singlepath_ + root->val, Right.singlepath_ + root->val, Root->val)        ; int doublepath = Getmax (Left.doublepath_, Right.doublepath_, Max(left.singlepath_ + right.singlepath_ + root->val, Singlepath));    Return ReturnType (Singlepath, Doublepath);     } int Getmax (int x, int y, int z) {return (x = x > y x:y) > z? x:z; }            };
7 Recent public ancestor
http://www.lintcode.com/zh-cn/problem/lowest-common-ancestor/Recent public ancestor

Given a binary tree, find the nearest common parent node (LCA) of two nodes.

The nearest public ancestor is a common ancestor node of two nodes and has the maximum depth.

Sample Example

For the following two-pronged tree

  4 / 3   7   /   5   6

LCA (3, 5) =4

LCA (5, 6) =7

LCA (6, 7) =7

如果两个节点都在同一棵子树中,则继续往该子树中查找。如果两个节点在不同的子树中,那么root即为最近公共祖先。

/** * 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) {//P,q are all in Zuozi if (Covers (Root->left, p) && covers (Root->left, q)) {return Lowestcommonancestor (root-&        Gt;left, Q, p); }//P,q are in the right subtree if (covers (Root->right, p) && covers (Root->right, q)) {return Lowes        Tcommonancestor (Root->right, Q, p);    }//Base case:p,q in a different subtree, or root is the return root of a node in p,q;    }//Helper function to determine if node p is in the subtree.        BOOL Covers (TreeNode *root, TreeNode *p) {if (root = NULL) {return false;        } if (root = = P) {return true; } return Covers (Root->left, p) | |    Covers (Root->right, p); }};
8 Convert Sorted Array to Binary Search Tree

Tree and other data structure conversion This type of problem requires that the structure of the trees be transformed into other data structures, such as linked list, array, or vice versa, from the structure of an array. Tree.

The former is usually through the traversal of the tree, the local solution to get the global solution, while the latter can benefit from the division of the strategy, recursive two parts of the data structure into a subtree, and then merge.

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

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

/** * 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* sortedarraytobst (vector<int>& nums) {return Sortedarraytobsthelpe    R (nums, 0, Nums.size ()-1);                } private:treenode* sortedarraytobsthelper (const vector<int> &nums, int start, int end) {        if (Start > End) {return NULL;        } if (start = = end) {return new TreeNode (Nums[start]);        } int mid = start + ((End-start) >> 1);        TreeNode *l = Sortedarraytobsthelper (Nums, start, mid-1);                TreeNode *r = Sortedarraytobsthelper (Nums, mid + 1, end);        TreeNode *root = new TreeNode (Nums[mid]);        Root->left = l;        Root->right = R;    return root; }};

9

[Algorithmic topic] Binary Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.