"The point of the sword" question 392 depth of the fork tree (Java)

Source: Internet
Author: User
Tags diff

Summary:

Today turned to the "point of the sword" face question 39, the second solution of the second is in the function of the parameter list by the way the pointer to the value, and Java is no pointer, so the function to be reformed. However, I turned down the Java version of others (I want to see what is the big change, after all, to pass a number of parameters, will it involve a little bit of design mode?). , I can only use a sentence to describe: "The seriousness of the nonsense ," but I just like to see you nonsense still fascinated by the look of confidence.

Let's Spit out this version of Java code:

1 //high-efficiency judgment is a balanced binary tree2      Public BooleanisBalanced2 (Binarytreenode root) {3         intDepth = 0; 4         returnIsBalanced2 (root,depth); 5     }  6      Public BooleanIsBalanced2 (Binarytreenode root,intdepth) {  7         if(Root = =NULL){  8Depth = 0; 9             return true; Ten         }   One         intleft = 0,right = 0;  A         if(IsBalanced2 (Root.leftnode,left) &&IsBalanced2 (root.rightnode,right)) {   -             intdiff = left-Right ;  -             if(diff <= 1 && diff >=-1){   thedepth = 1+ (left > right?)left:right);  -                 return true;  -             }   -         }   +         return false;  -}

The original link of this article I will not send, keep a bit of character. The key is special csdn unexpectedly put him as Baidu search the first top, visible popularity is the highest, see the author post history (as if there is a little bit of dick), I almost believed. This guy doesn't even know the value of the copy of the function parameter! How to learn the programming, also post misleading the vast number of pupils, simply can not endure. I don't have to refer to someone else's code, write one yourself.

First question: Enter the root node of a binary tree to find the depth of the tree. The nodes that pass from the root node to the leaf node (root, leaf node) Form a path, and the length of the longest path is the depth of the tree.

Input Sample:

1

2 3

4 5 6

7

Source:

classbinarytreenode{ Public intdata;  PublicBinarytreenode left;  PublicBinarytreenode right;  PublicBinarytreenode () {Data= 0; Left=NULL; Right=NULL; }} Public classquestion_39 {//----recursion to find the depth----of binary tree     Public Static inttreedepth (Binarytreenode root) {if(Root = =NULL){            return0; }        intleft =treedepth (Root.left); intright =treedepth (root.right); return(left>right)? (left+1):(right+1); }     Public Static voidMain (string[] args) {//TODO auto-generated Method StubBinarytreenode Node1 =NewBinarytreenode (); Binarytreenode Node2=NewBinarytreenode (); Binarytreenode Node3=NewBinarytreenode (); Binarytreenode Node4=NewBinarytreenode (); Binarytreenode Node5=NewBinarytreenode (); Binarytreenode Node6=NewBinarytreenode (); Binarytreenode Node7=NewBinarytreenode (); Node1.data= 1; Node2.data= 2; Node3.data= 3; Node4.data= 4; Node5.data= 5; Node6.data= 6; Node7.data= 7; Node1.left=Node2; Node1.right=Node3; Node2.left=Node4; Node2.right=Node5; Node5.left=Node7; Node3.right=Node6; System.out.println ("Recursion to find the depth of the binary tree:" +treedepth (Node1)); }}

This problem is relatively simple, there is nothing to say.

Topic Two: Enter a binary tree root node, to determine whether the tree is a balanced binary tree. If the depth of the left and right subtree of any node in a binary tree is not more than 1, then it is a balanced binary tree.

Method One: The solution that needs to iterate multiple times is simple but not enough to impress the interviewer

1  Public Static Booleanisbalanced_1 (Binarytreenode root) {2         if(root==NULL){3             return true;4         }5         intleft =treedepth (root.left);6         intright =treedepth (root.right);7         intdiff = left-Right ;8         if(diff>1| | Diff<-1){9             return false;Ten         } One         returnIsbalanced_1 (Root.left) &&isbalanced_1 (root.right); A}

The method is concise, but a node is iterated over multiple times, and the time efficiency is not high.

Method Two: Each node is traversed only once, the interviewer likes

1 classtuple{2     Private Booleanisbalanced;3     Private intdepth;4     5      PublicTuple () {}6      PublicTuple (BooleanIsbalanced,intdepth) {7         Super();8          This. isbalanced =isbalanced;9          This. depth =depth;Ten     } One     //-----isbalanced,getters and Setters---- A      Public Booleangetisbalanced () { -         returnisbalanced; -     } the      Public voidSetisbalanced (Booleanisbalanced) { -          This. isbalanced =isbalanced; -     } -     //-----depth,getters and Setters---- +      Public intgetdepth () { -         returndepth; +     } A      Public voidSetdepth (intdepth) { at          This. depth =depth; -     } -      -      - } - //----judge the balanced binary tree, each node is traversed only once---- in     Private StaticTuple isbalanced (binarytreenode root) { -         if(root==NULL){ toTuple tuple =NewTuple (); +Tuple.setisbalanced (true); -Tuple.setdepth (0); the             returntuple; *         } $Tuple left =isbalanced (root.left);Panax NotoginsengTuple right =isbalanced (root.right); -          the         if(Left.getisbalanced () &&right.getisbalanced ()) { +             intdiff = left.getdepth ()-right.getdepth (); A             if(Diff<=1&&diff>=-1){ the                 return NewTuple (true, (Left.getdepth () >right.getdepth () left.getdepth (): Right.getdepth ()) + 1 ); +             } -         } $         return  NewTuple (false,-1); $     } -      Public Static Booleanisbalancedbinarytree (Binarytreenode root) { -Tuple tuple =isbalanced (root); the         returntuple.getisbalanced (); -}

In the above code, we traverse the entire binary tree in the same way that we traverse it. After traversing the left and right sub-nodes of a node, we can judge the depth of the current node based on its deep-left node. When traversing to the root node, it is also judged that the whole binary tree is not a balanced binary tree. Due to the passing of two parameters, the usual method of using the return value is not feasible, and Java does not have a reference value for pointers and simple data types. The general high-level language (such as Python) will have tuples such a concept (Java does not have to define a), since only one value can be returned, then return a composite type, function transformation Complete ~

What I want to say is that every programmer who comes into the door knows that the parameter is a copy of the value, and that the value can be passed or fetched from the parameter list only by pointers and references, in Java, in addition to the base data type and string type, the reference value is also passed. But the basic data type passed into the function body What's the point of changing it? You just changed a copy. In order to protect the healthy growth of the next generation of programmers, the couple dedicated time to write a blog (key nose), to combat the bad wind ~ originally wanted and balanced binary tree together to write an article, but the balance of the two-tree TMD code to write 500 lines, I said it was frightened, have the opportunity to say

"The point of the sword" question 392 depth of the fork tree (Java)

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.