Tree-related issues on Leetcode

Source: Internet
Author: User
Tags diff
Preface

I did not expect that the junior still heavy schoolwork, coupled with some trivial, and their own inertia, many plans are not enough heart, but do not want to go on like this, recently reviewed his skills in the learning algorithm tree points, found that some of the basic algorithms and classical algorithms are really so little swallowed, So there is a brush Leetcode plan, one is to Restudying, the second is to familiarize yourself with Java or Python, the third is to keep the programming feel, four is for the future work to do a foreshadowing.

The goal is probably to spend the rest of your life using JAVA/PYTHON/C++/C to brush leetcode interesting questions . "In principle, the Java,second python,third C + +"

The specific plan is not, the impression of the university, as long as the said or written out plans will be interrupted by a variety of force majeure factors (such as this blog has a lot to be continued to the pit. ), so can brush one problem is a problem, can learn a little, blog as far as possible, the end of this semester is the main busy graduate study, and these two months is also a variety of test reports to be released to deal with, so. This TM is a big hole again. Easy Problem 100. Same Tree

Determine whether two trees are the same. train of Thought

See Code. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * */Public
class Solution {public
    boolean issametree (TreeNode p, TreeNode q) {
        if (p = = null & & q = null) return
            true;
        if (p = = NULL && q!= null) return
            false;
        if (p!= null && q = null) return
            false;
        if (p!= null && q!= null && p.val = q.val) return
            issametree (P.left, q.left) && Issametree (P.right, q.right);
        return false;
    }
}
Problem 101. Symmetric Tree the

To judge whether a binary tree is mirrored and symmetrical

Recursive writing should be concise. Code

//recursive/** * Definition for a binary tree node.
 * public class TreeNode {* int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode (int x) {val = x;} * */public class Solution {public boolean mysymmetric (TreeNode leftnode, TreeNode rightnode) {if (Leftno De!= null && rightnode!= null && leftnode.val = = rightnode.val) return Mysymmetric (Leftnode.
        Left, Rightnode.right) && mysymmetric (Leftnode.right, rightnode.left);
        else if (Leftnode = = NULL && Rightnode = null) return true;
    else return false;
        public Boolean issymmetric (TreeNode root) {if (root = null) return true;
    else return Mysymmetric (Root.left, root.right); }
}
Iterative
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 *
 /Public
class Solution {public
    Boolean issymmetric (TreeNode root) {
        queue<treenode> q = New LinkedList ();
        Q.add (root);
        Q.add (root);
        while (!q.isempty ()) {
            TreeNode Leftnode = Q.poll ();
            TreeNode Rightnode = Q.poll ();
            if (Leftnode = = NULL && Rightnode = null) continue;
            else if (Leftnode = null | | rightnode = NULL) return false;
            else if (leftnode.val!= rightnode.val) return false;
            Q.add (leftnode.left);
            Q.add (rightnode.right);
            Q.add (leftnode.right);
            Q.add (Rightnode.left);
        }
        return true;
    }
Problem 102. Binary Tree Level order traversal the

The element thought of each layer of the output binary tree

There is no difficulty in thinking, that is, the grammatical entanglement.
The various methods and implementations of List can refer to this:
The realization of ArrayList method
List interface and use sample code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 */
 public
class Solution {public

    list<list<integer>> treelist = new Arraylist<list <Integer>> ();

    public void traversal (TreeNode root, int depth) {
        if (root = null) return;
        if (treelist.size () = = depth) Treelist.add (new arraylist<integer> ());
        Treelist.get (Depth). Add (root.val);
        Traversal (root.left, depth + 1);
        Traversal (root.right, depth + 1);
    }

    Public list<list<integer>> Levelorder (TreeNode root) {
        traversal (root, 0);
        Return treelist
    }
}
Problem 107. Binary Tree Level order traversal II the

Starting from the bottom of a binary tree to output the value of each layer node

102 small step, no difficulty, if it is CPP or Python can directly use the reverse function on the line, do not know why the Java Collections.reverse () not. So directly changed the list insertion position.
Update:Collections.reverse () "No return value" can also be code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 */
 public
class Solution {public

    list<list<integer>> treelist = new Arraylist<list <Integer>> ();

    public void traversal (TreeNode root, int depth) {
        if (root = null) return;
        if (treelist.size () = = depth) treelist.add (0, New arraylist<integer> ());
        Treelist.get (Treelist.size ()-depth-1). Add (root.val);
        Traversal (root.left, depth + 1);
        Traversal (root.right, depth + 1);
    }

    Public list<list<integer>> Levelorderbottom (TreeNode root) {
        traversal (root, 0);        Collections.reverse (treelist);
        Return treelist
    }
}
Problem 110. Balanced Binary Tree the

To determine whether a binary tree is balanced (the height of the left and right subtree is not more than 1)

It's OK to ask for the height. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * */Public
class Solution {public
    int getdepth (TreeNode root) {
        if (root = null) return 
            0;
  else return Math.max (getdepth (Root.left), getdepth (root.right)) + 1;
    }

    public Boolean isbalanced (TreeNode root) {
        if (root = null) return
            true;
        int leftdepth = getdepth (root.left);
        int rightdepth = getdepth (root.right);
        int diff = Math.Abs (leftdepth-rightdepth);
        if (diff > 1) return false;
        else return isbalanced (root.left) && isbalanced (root.right);
    }
Problem 111. Minimum Depth of Binary tree the

Find out how many nodes to the shortest path of a binary root node to the nearest leaf node. train of Thought

And the idea of seeking altitude is similar. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * */Public
class Solution {public
    int mindepth (TreeNode root) {
        if (root = null) return
            0;
  if (Root.left = = NULL && root.right = null) return
            1;
        else if (root.left!= null && root.right = null) return
            mindepth (root.left) + 1;
        else if (Root.left = = null && root.right!= null) return
            mindepth (root.right) + 1;
        else return Math.min (mindepth (Root.left), mindepth (root.right)) + 1;
    }
Problem 112. Path Sum the

Enter a binary tree with an integer sum, and ask if there is a path to the root node to the leaf node, so that the sum of the node values that the path passes is exactly equal to sums. train of Thought

A common DFS. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * */Public
class Solution {public
    Boolean haspathsum (TreeNode root, int sum) {
        if (root = null) r Eturn false;
        else if (Root.left = null && root.right = null && sum = = Root.val) return 
            true;
        else return Haspathsum (Root.left, sum-root.val) | | Haspathsum (Root.right, sum-root.val);
    }
Problem 226. Invert Binary Tree the

Just invert a binary tree.
PS. The legend to kill Max Howell Google face test 233 thinking

Still Common Dfs ... Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 * */Public
class Solution {public
    TreeNode inverttree (TreeNode root) {
        if (root = null)
            RET Urn Root;
        TreeNode right = Inverttree (root.right);
        TreeNode left = Inverttree (root.left);
        Root.left = right;
        Root.right = left;
        return root;
    }
}
Problem 235. Lowest Common Ancestor of a Binary Search tree the

Enter a BST, as well as two nodes p,q, to ask for P and Q's LCA. train of Thought

Because of the characteristics of BST (left small right), the value of the LCA node of P and Q must be between p and Q values, i.e. Pval≤lcaval≤qval p_{val} \leq Lca_{val} \leq Q_{val}
So the Dfs starts from the root node until a node that meets this condition is found.

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 *
 /Public
class Solution {public
    TreeNode lowestcommonancestor (TreeNode root, TreeNode p, TreeNode q) {
        if ((root.val-p.val) * (Root.val-q.val) <= 0) return
            root;
        else if (Root.val > Q.val) return
            lowestcommonancestor (Root.left, p, q);
        else return
            lowestcommonancestor (Root.right, p, q);
    }
Problem 257. Binary Tree Paths the

Input a binary tree, output all the root node to the leaf node path thinking

Not too familiar with Java, so it is written with Dfs. It's also easy to implement BFS if you use Python. Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 *
 /Public
class Solution {public
    list<string> pathlist = new arraylist<string> ();

    public void GetPath (TreeNode root, String path) {
        if (root = null) return;
        if (Root.left = = NULL && Root.right = null) {
            Pathlist.add (path + integer.tostring (root.val));
            return;
        }

        GetPath (root.left, Path + integer.tostring (root.val) + "->");
        GetPath (root.right, Path + integer.tostring (root.val) + "->");

    Public list<string> binarytreepaths (TreeNode root) {
        if (root = null) return
            pathlist;
        GetPath (Root, "");
        Return pathlist
    }
}
Medium Problem 94. Binary Tree inorder Traversal the

Sequential traversal of a binary tree (requires non-recursive implementation) train of thought

Iterative method, refer to pseudocode on wiki:

Iterativeinorder (node)
  parentstack = empty stack while
  (not Parentstack.isempty () or Node≠null)
    if (node≠n ull)
      Parentstack.push (node)
      node = node.left
    Else
      node = parentstack.pop ()
      Visit (node)
      node = Node.right
Code
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode (int x) {val = x;}
 *
 /Public
class Solution {public
    list<integer> inordertraversal (TreeNode root) {
        List <Integer> res = new arraylist<integer> ();
        if (root = null) return res;
        stack<treenode> s = new stack<treenode> ();
        while (Root!= null | |!s.empty ()) {while
            (root!= null) {
                s.push (root);
                root = Root.left;
            }
            root = S.pop ();
            Res.add (root.val);
            root = Root.right;
        }
        return res;
    }
Problem 96. Unique Binary Search Trees the

Enter a number of n, the output [1,.., n] can make up how many different BST. train of Thought

In fact, a few more tweets will find the answer to the Catalan number:
Cn=1n+1 (2n

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.