微软100题第4题(在二元树中找出和为某一值的所有路径)

来源:互联网 发布:win10找不到网络打印机 编辑:程序博客网 时间:2024/06/02 00:43

1scala版

package msimport scala.collection.mutable.ListBufferimport scala.collection.mutable.ListBuffer/** * 4.在二元树中找出和为某一值的所有路径(树)题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如 输入整数22和如下二元树    10    /   /    5    12   / \     4  7则打印出两条路径:10, 12和10, 5, 7。二元树节点的数据结构定义为:struct BinaryTreeNode // a node in the binary tree{int m_nValue; // value of nodeBinaryTreeNode *m_pLeft; // left child of nodeBinaryTreeNode *m_pRight; // right child of node}; */class PathTree{    var root:PathTreeNode=null    def buildPathTree(data:List[Int])={      if(data.length>0){        root=PathTreeNode(data(0))        if(data.length>1){          for(i<-1 until data.length){            insertNode(root,data(i))          }        }      }    }        private[this] def insertNode(parent:PathTreeNode,value:Int):Unit={      if(parent.data>value){        if(parent.left==null){           parent.left=PathTreeNode(value)        }else{          insertNode(parent.left,value)        }      }else{        if(parent.right==null){          parent.right=PathTreeNode(value)        }else{          insertNode(parent.right, value)        }      }    }        def printPreOrder(){      printNode(root)    }        private[this] def printNode(node:PathTreeNode):Unit={      if(node==null)return      else{        printNode(node.left)        print(node.data+"=>")        printNode(node.right)      }    }        def computeWeight(){      root.weight=root.data;      computeWeightNode(root.left,root.weight)      computeWeightNode(root.right,root.weight)    }        private[this] def computeWeightNode(node:PathTreeNode,top:Int){      if(node==null)return      else{        node.weight=node.data+top;        computeWeightNode(node.left,node.weight)        computeWeightNode(node.right,node.weight)      }    }        def printPath(value:Int){      computeWeight();      val tmp=root.left      root.left=null      printPathNode(value,root,tmp)      printPathNode(value,root,root.right)          }        private[this] def printPathNode(value:Int,parent:PathTreeNode,child:PathTreeNode){      if(child!=null){          val tmp=child.left;          val leftNull=child.left==null;          val rightNull=child.right==null          child.left=parent ;          printPathNode(value,child,tmp)              printPathNode(value,child, child.right)          if(leftNull&&rightNull&&child.weight==value){            var node=child;            var listBuffer=ListBuffer[Int]();            while(node!=null){              listBuffer+=node.data              node=node.left            }            println()            for(i<-(0 until listBuffer.length).reverse){              print(listBuffer(i)+"=>")            }          }      }          }}case class PathTreeNode(val data:Int,var left:PathTreeNode=null,var right:PathTreeNode=null,var weight:Int=0)object MicroSoft004 {  def main(args: Array[String]): Unit = {    val data=List(10,5,4,7,12)    val tree=new PathTree()    tree.buildPathTree(data)    tree.printPreOrder()    tree.printPath(22)  }}

2java版

http://blog.csdn.net/hxpjava1/article/details/22104547

3python版

'''Created on 2017-1-17@author: admin/**  * 4.在二元树中找出和为某一值的所有路径(树) 题目:输入一个整数和一棵二元树。 从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。 打印出和与输入整数相等的所有路径。 例如 输入整数22和如下二元树     10     /   /     5    12    / \      4  7 则打印出两条路径:10, 12和10, 5, 7。 二元树节点的数据结构定义为: struct BinaryTreeNode // a node in the binary tree { int m_nValue; // value of node BinaryTreeNode *m_pLeft; // left child of node BinaryTreeNode *m_pRight; // right child of node };  */ '''from _overlapped import NULLclass PathTree:    def __init__(self,data):        if len(data)>0:            self.root=Node(data[0])            if(len(data)>1):                for i in range(1,len(data)):                    self._insertNode(self.root,data[i])    def _insertNode(self,parent,value):        if parent.value>value:            if parent.left==NULL:                parent.left=Node(value)            else:                self._insertNode(parent.left, value)        else:            if parent.right==NULL:                parent.right=Node(value)            else:                self._insertNode(parent.right, value)    def printPreOrder(self):        self._printNode(self.root)    def _printNode(self,parent):        if parent==NULL:            return;        self._printNode(parent.left)        print(parent.value,end="=>")        self._printNode(parent.right)        def printPath(self,pathValue):        tmp=self.root.left        self.root.left=NULL        self._printPath(self.root, self.root.value, tmp,pathValue)        self._printPath(self.root, self.root.value, self.root.right,pathValue)    def _printPath(self,parent,top,child,pathValue):        if child==NULL:            return;        leftTmp=child.left        child.left=parent                if leftTmp==NULL and child.right==NULL and (top+child.value)==pathValue:            tmp=child;            nodeList=[]            while tmp!=NULL:                nodeList.append(tmp.value)                tmp=tmp.left              print("")            for i in range(0,len(nodeList)):                print(nodeList[i],end="=>")                self._printPath(child, top+child.value, leftTmp, pathValue)        self._printPath(child, top+child.value, child.right, pathValue)        class Node:    def __init__(self,value):        self.value=value        self.left=NULL        self.right=NULL        if __name__ == '__main__':    data=[10,5,4,7,12]    tree=PathTree(data)    tree.printPreOrder()    tree.printPath(22)

c语言版本

/* * microsoft004.c * *  Created on: 2017年1月26日 *      Author: admin 4.在二元树中找出和为某一值的所有路径(树)题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如 输入整数22和如下二元树    10  /   / 5    12/ \4  7则打印出两条路径:10, 12和10, 5, 7。二元树节点的数据结构定义为:struct BinaryTreeNode // a node in the binary tree{int m_nValue; // value of nodeBinaryTreeNode *m_pLeft; // left child of nodeBinaryTreeNode *m_pRight; // right child of node}; */#include <stdio.h>#include <stdlib.h>#define MAX_DEPTH 100typedef struct BinaryTreeNode{int value;struct BinaryTreeNode * left;struct BinaryTreeNode * right;} node;node * root;int sum=0;void initTree();void freeTree(node * parent);void compute(node * parent,node * this,int topValue);int main4(){sum=22;initTree();node * left=root->left;root->left=NULL;compute(root,left,root->value);compute(root,root->right,root->value);//freeTree(root);return 0;}void initTree(){node * n1=(node*)malloc(sizeof(node));n1->value=10;root=n1;node * n2=(node*)malloc(sizeof(node));n2->value=5;node * n3=(node*)malloc(sizeof(node));n3->value=12;n3->left=NULL;n3->right=NULL;root->left=n2;root->right=n3;node * n4=(node*)malloc(sizeof(node));n4->value=4;n4->left=NULL;n4->right=NULL;node * n5=(node*)malloc(sizeof(node));n5->value=7;n5->left=NULL;n5->right=NULL;n2->left=n4;n2->right=n5;}void freeTree(node * parent){if(parent!=NULL){freeTree(parent->left);freeTree(parent->right);free(parent);}}void compute(node * parent,node * this,int topLeverValue){if(this==NULL){return;}int value=this->value+topLeverValue;node * left=this->left;this->left=parent;compute(this,left,value);compute(this,this->right,value);if(value==sum){if(left==NULL&&this->right==NULL){node * tmp=this;node * ary[MAX_DEPTH];int i=0;while(tmp!=NULL){ary[i++]=tmp;tmp=tmp->left;}for(--i;i>=0;i--){printf("%d->",ary[i]->value);}printf("\n");}}}

c++版本

/* * microsoft004.cpp * *  Created on: 2017年2月6日 *      Author: admin 4.在二元树中找出和为某一值的所有路径(树)题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。例如 输入整数22和如下二元树    10  /   / 5    12/ \4  7则打印出两条路径:10, 12和10, 5, 7。二元树节点的数据结构定义为:struct BinaryTreeNode // a node in the binary tree{int m_nValue; // value of nodeBinaryTreeNode *m_pLeft; // left child of nodeBinaryTreeNode *m_pRight; // right child of node}; */#include "iostream"using namespace std;class BinaryTreeNode{public:BinaryTreeNode(int value,BinaryTreeNode*left=NULL,BinaryTreeNode*right=NULL){this->value=value;this->left=left;this->right=right;}public:BinaryTreeNode*& getLeft()  {return left;}void setLeft( BinaryTreeNode* left) {this->left = left;}BinaryTreeNode*& getRight()  {return right;}void setRight( BinaryTreeNode* right) {this->right = right;}int getValue()  {return value;}void setValue(int value) {this->value = value;}private:int value;BinaryTreeNode * left;BinaryTreeNode * right;};class BinaryTree{public:BinaryTree(){this->sum=22;this->root=new BinaryTreeNode(10);this->root->setLeft(new BinaryTreeNode(5));this->root->setRight(new BinaryTreeNode(12));this->root->getLeft()->setLeft(new BinaryTreeNode(4));this->root->getLeft()->setRight(new BinaryTreeNode(7));}public:void searchPath(){BinaryTreeNode* left=root->getLeft();root->setLeft(NULL);searchPath(root,left,root->getValue());searchPath(root,root->getRight(),root->getValue());}private:void searchPath(BinaryTreeNode* parent,BinaryTreeNode* node,int topSum){if(node==NULL){return;}BinaryTreeNode* left=node->getLeft();node->setLeft(parent);if(topSum+node->getValue()==sum){if(left==NULL&&node->getRight()==NULL){BinaryTreeNode* tmp=node;while(tmp!=NULL){cout<<tmp->getValue()<<"=》";tmp=tmp->getLeft();}cout<<endl;}}searchPath(node,left,topSum+node->getValue());searchPath(node,node->getRight(),topSum+node->getValue());}private:BinaryTreeNode * root;int sum;};int main(){BinaryTree tree;tree.searchPath();return 0;}



0 0