print leaf nodes of binary tree [closed] - binary-tree

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am wrriting a recursive function that prints out leaf nodes of a binary tree.
Here's what I have so far:
public static void printLeafNodes(BinaryNode<AnyType> t)
{
if(t == NULL)
return;
if(t.left == NULL && t.right==NULL)
System.out.println(t.element);
else if(t.left != NULL && t.right == NULL)
printLeafNodes(t.left);
else
printLeafNodes(t.right);
}
I would very much appreciate if someone can pinpoint any flows in my logic.
Thanks.

public static void printLeafNodes(BinaryNode<AnyType> t)
{
if(t == NULL)
return;
if(t.left == NULL && t.right==NULL)
System.out.println(t.element);
printLeafNodes(t.left);
printLeafNodes(t.right);
}

Related

How to increase performance of this code snippet by assembly? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I increase performance of the following code snippet in assembly? Please suggest what ways I have in order to do this?
void changeDirection(char key) {
/*
W
A + D
S
*/
switch (key) {
case 'w':
if (direction != 2) direction = 0;
break;
case 'd':
if (direction != 3) direction = 1;
break;
case 's':
if (direction != 4) direction = 2;
break;
case 'a':
if (direction != 5) direction = 3;
break;
}
}/******increase performance*****/
Thanks
Actually in the end the 2-5 range vs 0-3 range turned out to be simple to abuse (although I'm afraid it's not what you wanted).
Plus normal games allow for key redefinition, which would break this completely. So this is more like "joke" than serious answer. But your question is on the brink of "joke" too, I mean: you have more serious problems if you really believe that the thing in your post is a problem.
// I expect "direction" to be int, otherwise change wantDir vars
void changeDirection2(char key) {
// a s d w
constexpr static int wantDir[] = { ~0, 3, ~0, 2, 1, ~0, ~0, 0 };
int wantedDir = wantDir[key&7];
if (wantedDir+2 == direction) return;
direction = wantedDir;
}
Plus this will react to many more (all of them) keys than a,w,s,d. It's up to caller call only with correct ones.
version 2, without LUT (still hardcoded to "awsd" and mangling any other key into some number):
void changeDirection3(char key) {
int wantedDir = (~key>>1)&3;
if (wantedDir+2 == direction) return;
direction = wantedDir;
}

KNight MOVe shortest [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
MY code is here: Question is to find min number of moves to go from one sq. to other in 8*8 chess board .
#include<iostream>
using namespace std;
int n;
int a[12][12];
int min1=1000,xd=5,yd=2,ys,xs,xsi,ysi;
int find_path(int xs,int ys)
{
cout<<xs<<" "<<ys<<endl;
if((xs==xd) && (ys==yd)) { cout<<"destiny schieved "<<endl; return 0;}
if(a[xs][ys]==1 || xs<0 || ys<0 || xs>7 || ys>7) return 10000;
a[xs][ys]=1;
int a1=1+(find_path(xs-2,ys+1)) ;
int b=1+(find_path(xs-2,ys-1)) ;
int c=1+(find_path(xs-1,ys+2)) ;
int d=1+(find_path(xs-1,ys-2)) ;
int d=1+(find_path(xs+2,ys+1)) ;
int e=1+(find_path(xs+2,ys-1)) ;
int f=1+(find_path(xs+1,ys+2)) ;
int g=1+(find_path(xs+1,ys-2)) ;
a[xs][ys]=0;
return min(a1,b,c,d,e,f,g);
}
int main()
{
int i,j,k;
for(i=0;i<8;i++)
for(j=0;j<8;j++)
a[i][j]=0;
cout<<"start"<<endl;
cout<<find_path(0,7);
system("pause");
return 0;
}
This is my code for traversing from one square to other in 8*8 chess board .
MY code gives wrong answer for some cases :
a[xs][ys]=1; is for preventing loops.
for eg answer for (0,7) ->>>> (5,2) is 4 but my algo gives 38 . MY coordinate axis are X: from left to right and Y-axis: from top to bottom . Please help me solving my problem.
Few solutions are:
(7,0) ->>> (0,7) : 6
(0,7) ->>> (5,2) :4
I have also tried another code which i later edited to get the above code:
int find_path(int xs,int ys,int path)
{
cout<<xs<<" "<<ys<<endl;
if((xs==xd) && (ys==yd)) { if(min1>path) min1=path; cout<<"destiny schieved "<<path<<endl; return 1;}
if(a[xs][ys]==1 || xs<0 || ys<0 || xs>7 || ys>7) return 0;
a[xs][ys]=1;
if(find_path(xs-2,ys+1,path+1)) {if(path==0) {cout<<"i am on start1"<<endl;} else return 1;}
if(find_path(xs-2,ys-1,path+1)) {if(path==0) {cout<<"i am on start2"<<endl;} else return 1; }
if(find_path(xs-1,ys+2,path+1)) {if(path==0) {cout<<"i am on start3"<<endl;} else return 1; }
if(find_path(xs-1,ys-2,path+1)) {if(path==0) {cout<<"i am on start4"<<endl;} else return 1;}
if(find_path(xs+2,ys+1,path+1)) {if(path==0) {cout<<"i am on start5"<<endl;} else return 1;}
if(find_path(xs+2,ys-1,path+1)) {if(path==0) {cout<<"i am on start6"<<endl;} else return 1;}
if(find_path(xs+1,ys+2,path+1)) {if(path==0) {cout<<"i am on start7"<<endl;} else return 1; }
if(find_path(xs+1,ys-2,path+1)) {if(path==0) {cout<<"i am on start8"<<endl;} else return 1; }
a[xs][ys]=0;
return 0;
}
It's often rewarding to think in terms of data structures instead of thinking in terms of algorithms.
In this case, the valid moves for a knight on a board constitute an undirected graph G where vertices denote board positions and edges denote valid moves. Hence, you might have nodes a1 and b3 connected by an edge, since a knight may move from a1 to b3 and vice versa.
Given that representation of the problem, it's fairly easy to compute the min number of moves for a knight to go from A to B, since it's the length of the shortest path from node A to node B in G.
to compute the shortest path for a given start node and all end nodes, use the Bellman-Ford algorithm with time complexity O(|V||E|).
to compute the shortest path for all pairs of nodes, use the Floyd-Warshall algorithm with time complexity O(|V|^3).

What is the Big O notation for this function? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have written a function and I need to know the big O notation for it.
I have tried to slove this myself and I get O(N^2), however I have been told that this is not the correct answer.
Can someone please tell me what the correct notation is and also a step by step explanation of how they came to that answer?
The function is below.
Thanks in advance
public static string Palindrome(string input)
{
string current = string.Empty;
string longest = string.Empty;
int left;
int center;
int right;
if (input == null || input == string.Empty || input.Length == 1) { return input; }
for (center = 1; center < input.Length -1; center++)
{
left = center - 1;
right = center + 1;
if (input[left] == input[center])
{
left--;
}
while (0 <= left && right < input.Length)
{
if (input[left] != input[right])
{
break;
}
current = input.Substring(left, (right - left + 1));
longest = current.Length > longest.Length ? current : longest;
left--;
right++;
}
}
return longest;
}
This is O(n^3) algorithm:
This part takes O(n^2):
// O(n) times for while loop
while (0 <= left && right < input.Length)
{
if (input[left] != input[right])
{
break;
}
// taking substring is O(n)
current = input.Substring(left, (right - left + 1));
longest = current.Length > longest.Length ? current : longest;
left--;
right++;
}
Also there is an outer O(n), for loop, which causes to O(n*n^2).
You can improve your algorithm by changing this lines:
current = input.Substring(left, (right - left + 1));
longest = current.Length > longest.Length ? current : longest;
to:
currentLength = right - left + 1;
if(currentLength > longest)
{
longest = current.Length > longest.Length ? current : longest;
longestLeft = left;
longestRight = right;
}
and finally return a substring from longestLeft to longestRight. Actually avoid to use substring method too many times.
The if (input[left] != input[right]) statement is executed O(n^2) times, and so are the several assignments following it, in particular:
current = input.Substring(left, (right - left + 1));
In typical implementations of substring functions, a sequence of characters is copied from the string to a new string object. The copy is an O(n) operation, leading to O(n^3) time for the loops and substring operation.
One can fix the problem by moving the assignments to current and longest to after the closing bracket of the while construct. But note that left--; and right++; will then have executed one time more than in the existing code, so the assignment to current becomes
current = input.Substring(left+1, (right-1 - (left+1) + 1));
or
current = input.Substring(left+1, (right-left-1));
Thus, the O(n) substring operation is done at most O(n) times.

Amazon Interview:Sum of the leaf node in BST

Code Which I have written for this :
sumBST(BST *root)
{
static sum =0;
if (root!= null)
{
if (root->left != null || root->right != null)
{
sum = sum + sumBST(root->left) + sumBST(root->right);
return sum;
}
else
{
root->data;
}
}
else
{
return 0;
}
return sum;
}
I have checked it by drawing recursion tree seems well but Still i am confused at some point I am doing some mistake. Please correct me i am doing something wrong here.
Well, it doesn't seem like you are actually adding the sum of the leaf nodes.
In parcticular - the line:
root->data
Does not actually return the data, just reads it.
Should be something like that in pseudo code:
sumBST(node):
if (root == null):
return 0
else if (root->left == null && root->right == null)
//add the value of the node if it is a leaf, this step is missing
return root->data;
else:
return sumBST(root->left) + sumBST(root->right)
EDIT:
The problem in the code are as follows (clarifying and explaining further that point in the answer):
You should return the data of the leaves somewhere - this is not happening anywhere in the code - I suspect you wanted to return it in root->data.
However note that the recursion will go to each and every leaf - it is just missing returning the value from each of them.
The purpose of such question is mainly focused on assessing the candidate thinking process.
All I see here is a typo error
root->data => return root->data
and an instruction that is never reached
return sum;
and one excessively long instruction
sum = sum + sumBST(root->left) + sumBST(root->right); => return sumBST(root->left) + sumBST(root->right);
Interviewers always like to get questioned about the problems they give.
A question like "Is the BST given or can I design a structure that is optimized toward given the sum of leaf?", "How big is the BST?"... Can add a plus and most likely change completely your answer.

Is there a way to implement a list using only stacks? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I wonder if there is a way to implement a list using only stacks. Is there?
You can make a (inefficient) list using two stacks. When you need to insert or retrieve an item, just move items from one stack to the other until you get the right index.
Here’s an example in JavaScript:
function List() {
this.stack1 = [];
this.stack2 = [];
Object.defineProperty(this, 'length', {
get: function() { return this.stack1.length + this.stack2.length; }
});
}
List.prototype.item = function(index) {
if(index < this.stack1.length) {
while(index < this.stack1.length - 1) {
this.stack2.push(this.stack1.pop());
}
return this.stack1[this.stack1.length - 1];
}
while(index > this.stack1.length) {
this.stack1.push(this.stack2.pop());
}
return this.stack2[this.stack2.length - 1];
};
List.prototype.insert = function(item, index) {
this.item(index - 1);
this.stack1.push(item);
};
by list, do you mean queue?becaue I can't see any connection between stack and list...
if so,you can use two stacks: s1 san s2 , imagine they are bottom to bottom. s1 is the head of a list and s2 is the tail.
functions of this list:
insert(ele):just use s2.push_back(ele)
pop():if s1 is not empty,s1.pop();else pop each element from s2 and push them into s1, then s1.pop()
size():s1.size()+s2.size()
...

Resources