The questions about the binary tree in "Leetcode"

Source: Internet
Author: User
Tags prev

112 Path Sum

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

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum =
5
/    \
4 8
/        / \
11 13 4
/   \               \
7 2 1

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

Ideas:

Determines whether the path of the root node of a binary tree to a leaf node is equal to a given value, has return true, and does not return false
Generally for the problem of binary trees, usually with the recursive return to solve, because the binary tree itself is a recursive structure.
1. Returns false if the node being traversed is null
2. If the node being traversed is a leaf node, the current path and the value of the current node will be judged to determine whether the present path is equal to the given path and is equal to return true and not equal to return false
3. If it is not a leaf node, then the same way to traverse the left and right subtree, the left and the child can only find a path

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * *
 /
class Solution {public
    Boolean haspathsum (TreeNode root, int sum) {
        if (root = null)
            RET Urn false;
        Return Haspathcore (root,sum,0);
    }
    Private Boolean Haspathcore (TreeNode root,int tarsum,int currsum) {
        if (root = null) return
            false;
        Currsum + = Root.val;
        Boolean isleaf = Root.left = = NULL && root.right = null;
        The leaf node
        if (isleaf) {
            //equals the target and, returns True, otherwise returns false
            if (currsum = = tarsum) return
                true;
            else return
                false;
        Zuozi or right subtree find a way to return to
        Haspathcore (root.left,tarsum,currsum) | | haspathcore (root.right,tarsum,currsum);

    }
}

113 Path Sum II

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

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum =
5
/    \
4 8
/        / \
11 13 4
/   \               \
7 2 1
return:

[
[5,4,11,2],
[5,8,4,5]
]

Ideas:

The last question adds a bit of difficulty, is to find the path to meet the goal and
The main idea has not changed, that is, in the process of finding a path, you need to add a qualifying path to the path

/** * Definition for a binary tree node.
 * public class TreeNode {* int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode (int x) {val = x;}
*}/import java.util.*;
    Class Solution {list<list<integer>> paths = new arraylist<> (); Public list<list<integer>> pathsum (TreeNode root, int sum) {list<integer> path = new arraylist&
        Lt;> ();
        if (root = null) return paths;
        Haspathcore (Root,sum,0,path);
    return paths;
            } private void Haspathcore (TreeNode root,int tarsum,int currsum,list<integer> path) {if (root = null)
        Return
        Currsum + = Root.val;
        Path.add (Root.val);
        Boolean isleaf = Root.left = = NULL && root.right = NULL;
            if (isleaf) {if (currsum = = tarsum) {//Find a path, join Paths Paths.add (path);
        }else return; //The next step is to find the node's leftWhether there is a China in the right subtree because the list is a reference pass, in order to not affect the current result in the depth traversal search, create a new list to pass the path that is currently found Haspathcore (root.left,tarsum,cur
        Rsum,new arraylist<> (path));
    Haspathcore (root.right,tarsum,currsum,new arraylist<> (path)); }
}

235.Lowest Common Ancestor of a Binary Search tree

Given A binary search tree (BST), and find the lowest common ancestor (LCA) of two Given, the BST.

According to the definition of LCA in Wikipedia: "The lowest common ancestor is defined between the two nodes V and W as the L Owest node in T so has both V and W as descendants (where we allow a node to be a descendant of itself). "

     _______6______
    /
 __2__           __8__
/      \        /      \
0       4       7       9
       /  \
       3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA the nodes 2 and 4 are 2, since a node can be a descendant of itself of the LCA definition.

Ideas:

This problem is the lowest common ancestor of two nodes in a binary search tree, in which nodes can be the lowest common ancestor of nodes themselves.
According to the binary ordered tree properties
1. Starting from the root node, if the value of the current node is greater than the value of two nodes, then two nodes of the lowest common ancestor must be located at the current node Zuozi
2. If the value is less than two nodes, then the right subtree must be located at the current node
3. If the current node value is greater than one node and is less than the other, then the lowest common ancestor is found

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * *
/class Solution {public
    TreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {
  
   if (root = = NULL) return
            null;
        while (root!= null) {
            int curr = root.val;
            int max = Math.max (p.val,q.val);
            int min = math.min (p.val,q.val);
            if (Curr > Max) {
                root = root.left;
            } else if (Curr < min)
                root = root.right;
            else return
                root;
        }
        return null;
    }
}
  

236.Lowest Common Ancestor of a Binary tree

Given a binary tree and find the lowest common ancestor (LCA) of two Given to the tree.

According to the definition of LCA in Wikipedia: "The lowest common ancestor is defined between the two nodes V and W as the L Owest node in T so has both V and W as descendants (where we allow a node to be a descendant of itself). "

     _______3______
    /
 __5__           __1__
/      \        /      \
6       2       0       8
       /  \
      7    4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA the nodes 5 and 4 are 5, since a node can be a descendant of itself of the LCA definition.

Ideas:

Given any binary tree, find the common ancestor of two nodes
Because it is not a binary search tree, it is not possible to traverse the nature of the binary tree
1. The current node is null and returns null
2. If the current node value is equal to any of the two nodes, the current node is the lowest common ancestor found (because we traverse from top to bottom, so that another unequal node must be below the node)
3. If not equal, then we repeat these two operations in the left subtree of the current node and in the right subtree to find these two nodes
4. If both the left and right are not empty, if both are found, then the current root is the lowest common ancestor; if one is not found, it can be concluded that the two nodes must be left subtrees at the current node or all in the right subtree, where the empty nodes are the lowest common ancestor

Public TreeNode lowestcommonancestor (TreeNode root,
                              TreeNode p, TreeNode q) {
        if (root = null) return
            null;< C3/>if (root = = P | | | root = q) return
            root;
        TreeNode left = Lowestcommonancestor (root.left,p,q);
        TreeNode right = Lowestcommonancestor (root.right,p,q);
        if (left!= null && right!= null) return
            root;
        return left = null? Right:left;
}

114.Flatten Binary to Linked List

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

For example, given the following tree:

     1
    /\
   2   5
  /\   \
  3   4   6

The flattened tree should look like:

1
\
2
\
3
\
4
\
5
\
6

Ideas:
Turning the two-fork tree into a two-fork tree with only the right child node, where we can find that the sequence of the right child's node is the result of the forward traversal, then, at the time of the conversion, we begin to revise the order of the nodes from the last-traversed node.
The most concise recursive implementation:
1. The current node is empty, return
2. Recursive right subtree, left subtree, the end result is to find the right leaf node
3. Find the most right leaf node is the final node, modify its left child pointer pointing to NULL and the previous traversal of the node, that is, we are from the right, left, the root of the order recursive traversal
4. Update the previous traversal of the node is the current node, return to the previous layer of recursion

Private TreeNode prev = null;
public void Flatten (TreeNode root) {
    if (root = null) return
        ;
    Flatten (root.right);
    Flatten (root.left);
    Root.right = prev;
    Root.left = null;
    prev = root;
}

Without recursion, use the stack to implement
The final sequence is actually the first root after the left child node final right child node order, then into the stack, you should first let the right child node into the stack, and then left the child node into the stack

public void Flatten (TreeNode root) {
        if (root = null) return;
        stack<treenode> s = new stack<> ();
        S.push (root);
        Records the previous traversal of the node, the current traversal of the node
        TreeNode prev = null, Curr = NULL;
        while (!s.isempty ()) {
            //pop-up stack top element
            Curr = S.pop ();
            If the previous traversal node is not empty, that is, a non-root node
            if (prev!= null) {
                //The right pointer of the previous node points to the current node
                prev.right = Curr; 
                prev.left=null;
            }
            The current node if the left and right child is not empty, then into the stack if
            (curr.right!= null) 
                s.push (curr.right);
            if (curr.left!= null) 
                s.push (curr.left);
            Update the previous traversal node
            prev = Curr;
        }
        Curr.right = null;
    }

199.Binary Tree Right Side View

Given a binary, imagine yourself standing on the right side to it, return the values of the nodes can From top to bottom.

Example:

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

1 <-1
/ \
2 3 <-3
\     \
5 4 <-4

Ideas:

In fact, each layer is traversed in sequence.
The output is the last element of each layer
Sequence traversal, which requires a queue, and because to determine whether the currently traversed element is the last element of the layer, so you need to record the number of each layer of elements, each access to a node, the number of elements-1, until reduced to 0, indicating that the layer node access completed, the last access node is the last node of the layer

/** * Definition for a binary tree node.
 * public class TreeNode {* int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode (int x) {val = x;}
*}/import java.util.*; Class Solution {public list<integer> rightsideview (TreeNode root) {list<integer> view = new Arra
        Ylist<> ();
        queue<treenode> q = new linkedlist<> (); 
        if (root = null) return view;
        Q.offer (root);
        int curr = 1;
        int next = 0;
            while (!q.isempty ()) {TreeNode node = Q.poll ();
                if (node.left!= null) {Q.offer (node.left);
            next++;
                } if (node.right!= null) {Q.offer (node.right);
            next++;
            } Curr--;
                if (Curr = = 0) {//update Curr Value Curr = next;
                Next is the next layer of knot number 0 next = 0;
    View.add (Node.val);        } return view; }///Someone else's code class Solution {public list<integer> rightsideview (TreeNode root) {list<integer> re
        Sult = new arraylist<> ();
        if (root = null) return result;
        queue<treenode> queue = new linkedlist<> ();
        Queue.offer (root);
            while (!queue.isempty ()) {int levelsize = Queue.size ();
                for (int i=0;i<levelsize;i++) {TreeNode node = Queue.poll ();
                if (i = = levelSize-1) result.add (node.val);
                if (node.left!= null) queue.offer (node.left);
            if (node.right!= null) queue.offer (node.right);
    } return result; }
}

105.Construct Binary tree from preorder and inorder traversal

Given Preorder and inorder traversal of a, construct the binary tree.

Note:
You could assume that duplicates does not exist into the tree.

For example, given

preorder = [3,9,20,15,7]
Inorder = [9,3,15,20,7]
Return to the following binary tree:

      3
     /
    9
    /    7

Ideas:

Create a two-fork tree based on the given sequence traversal sequence and the sequential traversal sequences
Using recursion
The first node of the preface is the root node, then the node can be found in the middle sequence sequence, then the left subtree of the node, the right subtree to the right of the node, and the subsequent construction process of the left subtree is still the same.

/** * Definition for a binary tree node.
 * public class TreeNode {* int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode (int x) {val = x;} * */class Solution {public TreeNode buildtree (int[] preorder, int[] inorder) {if (preorder = null | | ino Rder = = NULL | |
        Preorder.length!= inorder.length) return null;
    Return Buildtreecore (Preorder,inorder); Private TreeNode Buildtreecore (int[] preorder,int[] inorder) {if (preorder.length = 0 | | inorder.length = 0
        ) return null;
        TreeNode root = new TreeNode (preorder[0]); for (int i=0;i<inorder.length;i++) {if (inorder[i] = = Preorder[0]) {root.left = Buildtreecore
                (Arrays.copyofrange (preorder,1,i+1), Arrays.copyofrange (inorder,0,i)); Root.right = Buildtreecore (Arrays.copyofrange (preorder,i+1,preorder.length), Arrays.copyofrange (Inorder,i+1,
                Inorder.length));
            Break
     }   return root; }
}

106.Construct Binary tree from inorder and postorder traversal

Given Inorder and Postorder traversal of a, construct the binary tree.

Note:
You could assume that duplicates does not exist into the tree.

For example, given

Inorder = [9,3,15,20,7]
Postorder = [9,15,7,20,3]
Return to the following binary tree:

      3
     /
    9
    /    7

Ideas:

Given the sequence traversal and subsequent traversal sequence to create a two-fork tree, in fact, similar to the previous topic. The last node of the subsequent traversal is the root node, so we can find the root node in the sequence of the middle, the node on the left is the left subtree of the root, and the node on the right is the right subtree of the root.

/** * Definition for a binary tree node.
 * public class TreeNode {* int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode (int x) {val = x;} * */class Solution {public TreeNode buildtree (int[] inorder, int[] postorder) {if (inorder = null | | pos Torder = = NULL | |
        Inorder.length!= postorder.length) return null;
    Return Buildtreecore (Inorder,postorder);  Private TreeNode Buildtreecore (int[] inorder,int[] postorder) {if (inorder.length = 0 | | postorder.length = =
        0) return null;
        int len = postorder.length;
        TreeNode root = new TreeNode (postorder[len-1]); for (int i=0;i<inorder.length;i++) {if (postorder[len-1] = = Inorder[i]) {root.left = Buildt
                Reecore (Arrays.copyofrange (inorder,0,i), Arrays.copyofrange (postorder,0,i));
             Root.right = Buildtreecore (Arrays.copyofrange (inorder,i+1,inorder.length),   Arrays.copyofrange (postorder,i,len-1));
            Break
    } return root; }
}

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.